babylon.max.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. /**
  31. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  32. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  33. */
  34. var EffectFallbacks = /** @class */ (function () {
  35. function EffectFallbacks() {
  36. this._defines = {};
  37. this._currentRank = 32;
  38. this._maxRank = -1;
  39. }
  40. /**
  41. * Removes the fallback from the bound mesh.
  42. */
  43. EffectFallbacks.prototype.unBindMesh = function () {
  44. this._mesh = null;
  45. };
  46. /**
  47. * Adds a fallback on the specified property.
  48. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  49. * @param define The name of the define in the shader
  50. */
  51. EffectFallbacks.prototype.addFallback = function (rank, define) {
  52. if (!this._defines[rank]) {
  53. if (rank < this._currentRank) {
  54. this._currentRank = rank;
  55. }
  56. if (rank > this._maxRank) {
  57. this._maxRank = rank;
  58. }
  59. this._defines[rank] = new Array();
  60. }
  61. this._defines[rank].push(define);
  62. };
  63. /**
  64. * Sets the mesh to use CPU skinning when needing to fallback.
  65. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  66. * @param mesh The mesh to use the fallbacks.
  67. */
  68. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  69. this._mesh = mesh;
  70. if (rank < this._currentRank) {
  71. this._currentRank = rank;
  72. }
  73. if (rank > this._maxRank) {
  74. this._maxRank = rank;
  75. }
  76. };
  77. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  78. /**
  79. * Checks to see if more fallbacks are still availible.
  80. */
  81. get: function () {
  82. return this._currentRank <= this._maxRank;
  83. },
  84. enumerable: true,
  85. configurable: true
  86. });
  87. /**
  88. * Removes the defines that shoould be removed when falling back.
  89. * @param currentDefines defines the current define statements for the shader.
  90. * @param effect defines the current effect we try to compile
  91. * @returns The resulting defines with defines of the current rank removed.
  92. */
  93. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  94. // First we try to switch to CPU skinning
  95. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  96. this._mesh.computeBonesUsingShaders = false;
  97. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  98. var scene = this._mesh.getScene();
  99. for (var index = 0; index < scene.meshes.length; index++) {
  100. var otherMesh = scene.meshes[index];
  101. if (!otherMesh.material) {
  102. continue;
  103. }
  104. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  105. continue;
  106. }
  107. if (otherMesh.material.getEffect() === effect) {
  108. otherMesh.computeBonesUsingShaders = false;
  109. }
  110. else {
  111. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  112. var subMesh = _a[_i];
  113. var subMeshEffect = subMesh.effect;
  114. if (subMeshEffect === effect) {
  115. otherMesh.computeBonesUsingShaders = false;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. var currentFallbacks = this._defines[this._currentRank];
  124. if (currentFallbacks) {
  125. for (var index = 0; index < currentFallbacks.length; index++) {
  126. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  127. }
  128. }
  129. this._currentRank++;
  130. }
  131. return currentDefines;
  132. };
  133. return EffectFallbacks;
  134. }());
  135. BABYLON.EffectFallbacks = EffectFallbacks;
  136. /**
  137. * Options to be used when creating an effect.
  138. */
  139. var EffectCreationOptions = /** @class */ (function () {
  140. function EffectCreationOptions() {
  141. }
  142. return EffectCreationOptions;
  143. }());
  144. BABYLON.EffectCreationOptions = EffectCreationOptions;
  145. /**
  146. * Effect containing vertex and fragment shader that can be executed on an object.
  147. */
  148. var Effect = /** @class */ (function () {
  149. /**
  150. * Instantiates an effect.
  151. * An effect can be used to create/manage/execute vertex and fragment shaders.
  152. * @param baseName Name of the effect.
  153. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  154. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  155. * @param samplers List of sampler variables that will be passed to the shader.
  156. * @param engine Engine to be used to render the effect
  157. * @param defines Define statements to be added to the shader.
  158. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  159. * @param onCompiled Callback that will be called when the shader is compiled.
  160. * @param onError Callback that will be called if an error occurs during shader compilation.
  161. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  162. */
  163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  164. if (samplers === void 0) { samplers = null; }
  165. if (defines === void 0) { defines = null; }
  166. if (fallbacks === void 0) { fallbacks = null; }
  167. if (onCompiled === void 0) { onCompiled = null; }
  168. if (onError === void 0) { onError = null; }
  169. var _this = this;
  170. /**
  171. * Unique ID of the effect.
  172. */
  173. this.uniqueId = 0;
  174. /**
  175. * Observable that will be called when the shader is compiled.
  176. */
  177. this.onCompileObservable = new BABYLON.Observable();
  178. /**
  179. * Observable that will be called if an error occurs during shader compilation.
  180. */
  181. this.onErrorObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called when effect is bound.
  184. */
  185. this.onBindObservable = new BABYLON.Observable();
  186. this._uniformBuffersNames = {};
  187. this._isReady = false;
  188. this._compilationError = "";
  189. this.name = baseName;
  190. if (attributesNamesOrOptions.attributes) {
  191. var options = attributesNamesOrOptions;
  192. this._engine = uniformsNamesOrEngine;
  193. this._attributesNames = options.attributes;
  194. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  195. this._samplers = options.samplers;
  196. this.defines = options.defines;
  197. this.onError = options.onError;
  198. this.onCompiled = options.onCompiled;
  199. this._fallbacks = options.fallbacks;
  200. this._indexParameters = options.indexParameters;
  201. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  202. if (options.uniformBuffersNames) {
  203. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  204. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  205. }
  206. }
  207. }
  208. else {
  209. this._engine = engine;
  210. this.defines = defines;
  211. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  212. this._samplers = samplers;
  213. this._attributesNames = attributesNamesOrOptions;
  214. this.onError = onError;
  215. this.onCompiled = onCompiled;
  216. this._indexParameters = indexParameters;
  217. this._fallbacks = fallbacks;
  218. }
  219. this.uniqueId = Effect._uniqueIdSeed++;
  220. var vertexSource;
  221. var fragmentSource;
  222. if (baseName.vertexElement) {
  223. vertexSource = document.getElementById(baseName.vertexElement);
  224. if (!vertexSource) {
  225. vertexSource = baseName.vertexElement;
  226. }
  227. }
  228. else {
  229. vertexSource = baseName.vertex || baseName;
  230. }
  231. if (baseName.fragmentElement) {
  232. fragmentSource = document.getElementById(baseName.fragmentElement);
  233. if (!fragmentSource) {
  234. fragmentSource = baseName.fragmentElement;
  235. }
  236. }
  237. else {
  238. fragmentSource = baseName.fragment || baseName;
  239. }
  240. var finalVertexCode;
  241. this._loadVertexShaderAsync(vertexSource)
  242. .then(function (vertexCode) {
  243. return _this._processIncludesAsync(vertexCode);
  244. })
  245. .then(function (vertexCodeWithIncludes) {
  246. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  247. return _this._loadFragmentShaderAsync(fragmentSource);
  248. })
  249. .then(function (fragmentCode) {
  250. return _this._processIncludesAsync(fragmentCode);
  251. })
  252. .then(function (fragmentCodeWithIncludes) {
  253. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  254. if (baseName) {
  255. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  256. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  257. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  258. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  259. }
  260. else {
  261. _this._vertexSourceCode = finalVertexCode;
  262. _this._fragmentSourceCode = migratedFragmentCode;
  263. }
  264. _this._prepareEffect();
  265. });
  266. }
  267. Object.defineProperty(Effect.prototype, "key", {
  268. /**
  269. * Unique key for this effect
  270. */
  271. get: function () {
  272. return this._key;
  273. },
  274. enumerable: true,
  275. configurable: true
  276. });
  277. /**
  278. * If the effect has been compiled and prepared.
  279. * @returns if the effect is compiled and prepared.
  280. */
  281. Effect.prototype.isReady = function () {
  282. return this._isReady;
  283. };
  284. /**
  285. * The engine the effect was initialized with.
  286. * @returns the engine.
  287. */
  288. Effect.prototype.getEngine = function () {
  289. return this._engine;
  290. };
  291. /**
  292. * The compiled webGL program for the effect
  293. * @returns the webGL program.
  294. */
  295. Effect.prototype.getProgram = function () {
  296. return this._program;
  297. };
  298. /**
  299. * The set of names of attribute variables for the shader.
  300. * @returns An array of attribute names.
  301. */
  302. Effect.prototype.getAttributesNames = function () {
  303. return this._attributesNames;
  304. };
  305. /**
  306. * Returns the attribute at the given index.
  307. * @param index The index of the attribute.
  308. * @returns The location of the attribute.
  309. */
  310. Effect.prototype.getAttributeLocation = function (index) {
  311. return this._attributes[index];
  312. };
  313. /**
  314. * Returns the attribute based on the name of the variable.
  315. * @param name of the attribute to look up.
  316. * @returns the attribute location.
  317. */
  318. Effect.prototype.getAttributeLocationByName = function (name) {
  319. var index = this._attributesNames.indexOf(name);
  320. return this._attributes[index];
  321. };
  322. /**
  323. * The number of attributes.
  324. * @returns the numnber of attributes.
  325. */
  326. Effect.prototype.getAttributesCount = function () {
  327. return this._attributes.length;
  328. };
  329. /**
  330. * Gets the index of a uniform variable.
  331. * @param uniformName of the uniform to look up.
  332. * @returns the index.
  333. */
  334. Effect.prototype.getUniformIndex = function (uniformName) {
  335. return this._uniformsNames.indexOf(uniformName);
  336. };
  337. /**
  338. * Returns the attribute based on the name of the variable.
  339. * @param uniformName of the uniform to look up.
  340. * @returns the location of the uniform.
  341. */
  342. Effect.prototype.getUniform = function (uniformName) {
  343. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  344. };
  345. /**
  346. * Returns an array of sampler variable names
  347. * @returns The array of sampler variable neames.
  348. */
  349. Effect.prototype.getSamplers = function () {
  350. return this._samplers;
  351. };
  352. /**
  353. * The error from the last compilation.
  354. * @returns the error string.
  355. */
  356. Effect.prototype.getCompilationError = function () {
  357. return this._compilationError;
  358. };
  359. /**
  360. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  361. * @param func The callback to be used.
  362. */
  363. Effect.prototype.executeWhenCompiled = function (func) {
  364. if (this.isReady()) {
  365. func(this);
  366. return;
  367. }
  368. this.onCompileObservable.add(function (effect) {
  369. func(effect);
  370. });
  371. };
  372. /** @ignore */
  373. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  374. if (BABYLON.Tools.IsWindowObjectExist()) {
  375. // DOM element ?
  376. if (vertex instanceof HTMLElement) {
  377. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  378. return Promise.resolve(vertexCode);
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. return Promise.resolve(vertexBinary);
  385. }
  386. // Is in local store ?
  387. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  388. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  389. }
  390. var vertexShaderUrl;
  391. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  392. vertexShaderUrl = vertex;
  393. }
  394. else {
  395. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  396. }
  397. // Vertex shader
  398. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  399. };
  400. /** @ignore */
  401. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  402. if (BABYLON.Tools.IsWindowObjectExist()) {
  403. // DOM element ?
  404. if (fragment instanceof HTMLElement) {
  405. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  406. return Promise.resolve(fragmentCode);
  407. }
  408. }
  409. // Base64 encoded ?
  410. if (fragment.substr(0, 7) === "base64:") {
  411. var fragmentBinary = window.atob(fragment.substr(7));
  412. return Promise.resolve(fragmentBinary);
  413. }
  414. // Is in local store ?
  415. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  416. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  417. }
  418. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  419. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  420. }
  421. var fragmentShaderUrl;
  422. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  423. fragmentShaderUrl = fragment;
  424. }
  425. else {
  426. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  427. }
  428. // Fragment shader
  429. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  430. };
  431. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  432. // Rebuild shaders source code
  433. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  434. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  435. vertexCode = prefix + vertexCode;
  436. fragmentCode = prefix + fragmentCode;
  437. // Number lines of shaders source code
  438. var i = 2;
  439. var regex = /\n/gm;
  440. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  441. i = 2;
  442. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  443. // Dump shaders name and formatted source code
  444. if (this.name.vertexElement) {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  447. }
  448. else if (this.name.vertex) {
  449. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  450. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  451. }
  452. else {
  453. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  454. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  455. }
  456. };
  457. ;
  458. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  459. var preparedSourceCode = this._processPrecision(sourceCode);
  460. if (this._engine.webGLVersion == 1) {
  461. return preparedSourceCode;
  462. }
  463. // Already converted
  464. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  465. return preparedSourceCode.replace("#version 300 es", "");
  466. }
  467. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  468. // Remove extensions
  469. // #extension GL_OES_standard_derivatives : enable
  470. // #extension GL_EXT_shader_texture_lod : enable
  471. // #extension GL_EXT_frag_depth : enable
  472. // #extension GL_EXT_draw_buffers : require
  473. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  474. var result = preparedSourceCode.replace(regex, "");
  475. // Migrate to GLSL v300
  476. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  477. result = result.replace(/attribute[ \t]/g, "in ");
  478. result = result.replace(/[ \t]attribute/g, " in");
  479. if (isFragment) {
  480. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  481. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  482. result = result.replace(/texture2D\s*\(/g, "texture(");
  483. result = result.replace(/textureCube\s*\(/g, "texture(");
  484. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  485. result = result.replace(/gl_FragColor/g, "glFragColor");
  486. result = result.replace(/gl_FragData/g, "glFragData");
  487. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  488. }
  489. return result;
  490. };
  491. Effect.prototype._processIncludesAsync = function (sourceCode) {
  492. var _this = this;
  493. return new Promise(function (resolve, reject) {
  494. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  495. var match = regex.exec(sourceCode);
  496. var returnValue = sourceCode;
  497. while (match != null) {
  498. var includeFile = match[1];
  499. // Uniform declaration
  500. if (includeFile.indexOf("__decl__") !== -1) {
  501. includeFile = includeFile.replace(/__decl__/, "");
  502. if (_this._engine.supportsUniformBuffers) {
  503. includeFile = includeFile.replace(/Vertex/, "Ubo");
  504. includeFile = includeFile.replace(/Fragment/, "Ubo");
  505. }
  506. includeFile = includeFile + "Declaration";
  507. }
  508. if (Effect.IncludesShadersStore[includeFile]) {
  509. // Substitution
  510. var includeContent = Effect.IncludesShadersStore[includeFile];
  511. if (match[2]) {
  512. var splits = match[3].split(",");
  513. for (var index = 0; index < splits.length; index += 2) {
  514. var source = new RegExp(splits[index], "g");
  515. var dest = splits[index + 1];
  516. includeContent = includeContent.replace(source, dest);
  517. }
  518. }
  519. if (match[4]) {
  520. var indexString = match[5];
  521. if (indexString.indexOf("..") !== -1) {
  522. var indexSplits = indexString.split("..");
  523. var minIndex = parseInt(indexSplits[0]);
  524. var maxIndex = parseInt(indexSplits[1]);
  525. var sourceIncludeContent = includeContent.slice(0);
  526. includeContent = "";
  527. if (isNaN(maxIndex)) {
  528. maxIndex = _this._indexParameters[indexSplits[1]];
  529. }
  530. for (var i = minIndex; i < maxIndex; i++) {
  531. if (!_this._engine.supportsUniformBuffers) {
  532. // Ubo replacement
  533. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  534. return p1 + "{X}";
  535. });
  536. }
  537. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  538. }
  539. }
  540. else {
  541. if (!_this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent = includeContent.replace(/\{X\}/g, indexString);
  548. }
  549. }
  550. // Replace
  551. returnValue = returnValue.replace(match[0], includeContent);
  552. }
  553. else {
  554. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  555. _this._engine._loadFileAsync(includeShaderUrl)
  556. .then(function (fileContent) {
  557. Effect.IncludesShadersStore[includeFile] = fileContent;
  558. return _this._processIncludesAsync(returnValue);
  559. })
  560. .then(function (returnValue) {
  561. resolve(returnValue);
  562. });
  563. return;
  564. }
  565. match = regex.exec(sourceCode);
  566. }
  567. resolve(returnValue);
  568. });
  569. };
  570. Effect.prototype._processPrecision = function (source) {
  571. if (source.indexOf("precision highp float") === -1) {
  572. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  573. source = "precision mediump float;\n" + source;
  574. }
  575. else {
  576. source = "precision highp float;\n" + source;
  577. }
  578. }
  579. else {
  580. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  581. source = source.replace("precision highp float", "precision mediump float");
  582. }
  583. }
  584. return source;
  585. };
  586. /**
  587. * Recompiles the webGL program
  588. * @param vertexSourceCode The source code for the vertex shader.
  589. * @param fragmentSourceCode The source code for the fragment shader.
  590. * @param onCompiled Callback called when completed.
  591. * @param onError Callback called on error.
  592. */
  593. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  594. var _this = this;
  595. this._isReady = false;
  596. this._vertexSourceCodeOverride = vertexSourceCode;
  597. this._fragmentSourceCodeOverride = fragmentSourceCode;
  598. this.onError = function (effect, error) {
  599. if (onError) {
  600. onError(error);
  601. }
  602. };
  603. this.onCompiled = function () {
  604. var scenes = _this.getEngine().scenes;
  605. for (var i = 0; i < scenes.length; i++) {
  606. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  607. }
  608. if (onCompiled) {
  609. onCompiled(_this._program);
  610. }
  611. };
  612. this._fallbacks = null;
  613. this._prepareEffect();
  614. };
  615. /**
  616. * Gets the uniform locations of the the specified variable names
  617. * @param names THe names of the variables to lookup.
  618. * @returns Array of locations in the same order as variable names.
  619. */
  620. Effect.prototype.getSpecificUniformLocations = function (names) {
  621. var engine = this._engine;
  622. return engine.getUniforms(this._program, names);
  623. };
  624. /**
  625. * Prepares the effect
  626. */
  627. Effect.prototype._prepareEffect = function () {
  628. var attributesNames = this._attributesNames;
  629. var defines = this.defines;
  630. var fallbacks = this._fallbacks;
  631. this._valueCache = {};
  632. var previousProgram = this._program;
  633. try {
  634. var engine = this._engine;
  635. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  636. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  637. }
  638. else {
  639. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  640. }
  641. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  642. if (engine.supportsUniformBuffers) {
  643. for (var name in this._uniformBuffersNames) {
  644. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  645. }
  646. }
  647. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  648. this._attributes = engine.getAttributes(this._program, attributesNames);
  649. var index;
  650. for (index = 0; index < this._samplers.length; index++) {
  651. var sampler = this.getUniform(this._samplers[index]);
  652. if (sampler == null) {
  653. this._samplers.splice(index, 1);
  654. index--;
  655. }
  656. }
  657. engine.bindSamplers(this);
  658. this._compilationError = "";
  659. this._isReady = true;
  660. if (this.onCompiled) {
  661. this.onCompiled(this);
  662. }
  663. this.onCompileObservable.notifyObservers(this);
  664. this.onCompileObservable.clear();
  665. // Unbind mesh reference in fallbacks
  666. if (this._fallbacks) {
  667. this._fallbacks.unBindMesh();
  668. }
  669. if (previousProgram) {
  670. this.getEngine()._deleteProgram(previousProgram);
  671. }
  672. }
  673. catch (e) {
  674. this._compilationError = e.message;
  675. // Let's go through fallbacks then
  676. BABYLON.Tools.Error("Unable to compile effect:");
  677. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  678. return " " + uniform;
  679. }));
  680. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  681. return " " + attribute;
  682. }));
  683. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  684. BABYLON.Tools.Error("Error: " + this._compilationError);
  685. if (previousProgram) {
  686. this._program = previousProgram;
  687. this._isReady = true;
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. }
  693. if (fallbacks && fallbacks.isMoreFallbacks) {
  694. BABYLON.Tools.Error("Trying next fallback.");
  695. this.defines = fallbacks.reduce(this.defines, this);
  696. this._prepareEffect();
  697. }
  698. else {
  699. if (this.onError) {
  700. this.onError(this, this._compilationError);
  701. }
  702. this.onErrorObservable.notifyObservers(this);
  703. this.onErrorObservable.clear();
  704. // Unbind mesh reference in fallbacks
  705. if (this._fallbacks) {
  706. this._fallbacks.unBindMesh();
  707. }
  708. }
  709. }
  710. };
  711. Object.defineProperty(Effect.prototype, "isSupported", {
  712. /**
  713. * Checks if the effect is supported. (Must be called after compilation)
  714. */
  715. get: function () {
  716. return this._compilationError === "";
  717. },
  718. enumerable: true,
  719. configurable: true
  720. });
  721. /**
  722. * Binds a texture to the engine to be used as output of the shader.
  723. * @param channel Name of the output variable.
  724. * @param texture Texture to bind.
  725. */
  726. Effect.prototype._bindTexture = function (channel, texture) {
  727. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  728. };
  729. /**
  730. * Sets a texture on the engine to be used in the shader.
  731. * @param channel Name of the sampler variable.
  732. * @param texture Texture to set.
  733. */
  734. Effect.prototype.setTexture = function (channel, texture) {
  735. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  736. };
  737. /**
  738. * Sets an array of textures on the engine to be used in the shader.
  739. * @param channel Name of the variable.
  740. * @param textures Textures to set.
  741. */
  742. Effect.prototype.setTextureArray = function (channel, textures) {
  743. if (this._samplers.indexOf(channel + "Ex") === -1) {
  744. var initialPos = this._samplers.indexOf(channel);
  745. for (var index = 1; index < textures.length; index++) {
  746. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  747. }
  748. }
  749. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  750. };
  751. /**
  752. * 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)
  753. * @param channel Name of the sampler variable.
  754. * @param postProcess Post process to get the input texture from.
  755. */
  756. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  757. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  758. };
  759. /** @ignore */
  760. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  761. var cache = this._valueCache[uniformName];
  762. var flag = matrix.updateFlag;
  763. if (cache !== undefined && cache === flag) {
  764. return false;
  765. }
  766. this._valueCache[uniformName] = flag;
  767. return true;
  768. };
  769. /** @ignore */
  770. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  771. var cache = this._valueCache[uniformName];
  772. if (!cache) {
  773. cache = [x, y];
  774. this._valueCache[uniformName] = cache;
  775. return true;
  776. }
  777. var changed = false;
  778. if (cache[0] !== x) {
  779. cache[0] = x;
  780. changed = true;
  781. }
  782. if (cache[1] !== y) {
  783. cache[1] = y;
  784. changed = true;
  785. }
  786. return changed;
  787. };
  788. /** @ignore */
  789. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y, z];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. if (cache[2] !== z) {
  806. cache[2] = z;
  807. changed = true;
  808. }
  809. return changed;
  810. };
  811. /** @ignore */
  812. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  813. var cache = this._valueCache[uniformName];
  814. if (!cache) {
  815. cache = [x, y, z, w];
  816. this._valueCache[uniformName] = cache;
  817. return true;
  818. }
  819. var changed = false;
  820. if (cache[0] !== x) {
  821. cache[0] = x;
  822. changed = true;
  823. }
  824. if (cache[1] !== y) {
  825. cache[1] = y;
  826. changed = true;
  827. }
  828. if (cache[2] !== z) {
  829. cache[2] = z;
  830. changed = true;
  831. }
  832. if (cache[3] !== w) {
  833. cache[3] = w;
  834. changed = true;
  835. }
  836. return changed;
  837. };
  838. /**
  839. * Binds a buffer to a uniform.
  840. * @param buffer Buffer to bind.
  841. * @param name Name of the uniform variable to bind to.
  842. */
  843. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  844. var bufferName = this._uniformBuffersNames[name];
  845. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  846. return;
  847. }
  848. Effect._baseCache[bufferName] = buffer;
  849. this._engine.bindUniformBufferBase(buffer, bufferName);
  850. };
  851. /**
  852. * Binds block to a uniform.
  853. * @param blockName Name of the block to bind.
  854. * @param index Index to bind.
  855. */
  856. Effect.prototype.bindUniformBlock = function (blockName, index) {
  857. this._engine.bindUniformBlock(this._program, blockName, index);
  858. };
  859. /**
  860. * Sets an interger value on a uniform variable.
  861. * @param uniformName Name of the variable.
  862. * @param value Value to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setInt = function (uniformName, value) {
  866. var cache = this._valueCache[uniformName];
  867. if (cache !== undefined && cache === value)
  868. return this;
  869. this._valueCache[uniformName] = value;
  870. this._engine.setInt(this.getUniform(uniformName), value);
  871. return this;
  872. };
  873. /**
  874. * Sets an int array on a uniform variable.
  875. * @param uniformName Name of the variable.
  876. * @param array array to be set.
  877. * @returns this effect.
  878. */
  879. Effect.prototype.setIntArray = function (uniformName, array) {
  880. this._valueCache[uniformName] = null;
  881. this._engine.setIntArray(this.getUniform(uniformName), array);
  882. return this;
  883. };
  884. /**
  885. * 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)
  886. * @param uniformName Name of the variable.
  887. * @param array array to be set.
  888. * @returns this effect.
  889. */
  890. Effect.prototype.setIntArray2 = function (uniformName, array) {
  891. this._valueCache[uniformName] = null;
  892. this._engine.setIntArray2(this.getUniform(uniformName), array);
  893. return this;
  894. };
  895. /**
  896. * 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)
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray3 = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray3(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * 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)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray4 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray4(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an float array on a uniform variable.
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setFloatArray = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setFloatArray(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * 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)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * 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)
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * 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)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an array on a uniform variable.
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setArray = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setArray(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setArray2 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setArray2(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * 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)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray3 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray3(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * 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)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray4 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray4(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets matrices on a uniform variable.
  1007. * @param uniformName Name of the variable.
  1008. * @param matrices matrices to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1012. if (!matrices) {
  1013. return this;
  1014. }
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1017. return this;
  1018. };
  1019. /**
  1020. * Sets matrix on a uniform variable.
  1021. * @param uniformName Name of the variable.
  1022. * @param matrix matrix to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1026. if (this._cacheMatrix(uniformName, matrix)) {
  1027. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1028. }
  1029. return this;
  1030. };
  1031. /**
  1032. * 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)
  1033. * @param uniformName Name of the variable.
  1034. * @param matrix matrix to be set.
  1035. * @returns this effect.
  1036. */
  1037. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1038. this._valueCache[uniformName] = null;
  1039. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1044. * @param uniformName Name of the variable.
  1045. * @param matrix matrix to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a float on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param value value to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat = function (uniformName, value) {
  1060. var cache = this._valueCache[uniformName];
  1061. if (cache !== undefined && cache === value)
  1062. return this;
  1063. this._valueCache[uniformName] = value;
  1064. this._engine.setFloat(this.getUniform(uniformName), value);
  1065. return this;
  1066. };
  1067. /**
  1068. * Sets a boolean on a uniform variable.
  1069. * @param uniformName Name of the variable.
  1070. * @param bool value to be set.
  1071. * @returns this effect.
  1072. */
  1073. Effect.prototype.setBool = function (uniformName, bool) {
  1074. var cache = this._valueCache[uniformName];
  1075. if (cache !== undefined && cache === bool)
  1076. return this;
  1077. this._valueCache[uniformName] = bool;
  1078. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector2 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector2 vector2 to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1088. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1089. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float2 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float2.
  1097. * @param y Second float in float2.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1101. if (this._cacheFloat2(uniformName, x, y)) {
  1102. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1103. }
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets a Vector3 on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param vector3 Value to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1113. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1114. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a float3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param x First float in float3.
  1122. * @param y Second float in float3.
  1123. * @param z Third float in float3.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1127. if (this._cacheFloat3(uniformName, x, y, z)) {
  1128. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * Sets a Vector4 on a uniform variable.
  1134. * @param uniformName Name of the variable.
  1135. * @param vector4 Value to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1139. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1140. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1141. }
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a float4 on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param x First float in float4.
  1148. * @param y Second float in float4.
  1149. * @param z Third float in float4.
  1150. * @param w Fourth float in float4.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1154. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1155. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color3 on a uniform variable.
  1161. * @param uniformName Name of the variable.
  1162. * @param color3 Value to be set.
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setColor3 = function (uniformName, color3) {
  1166. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1167. this._engine.setColor3(this.getUniform(uniformName), color3);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a Color4 on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param color3 Value to be set.
  1175. * @param alpha Alpha value to be set.
  1176. * @returns this effect.
  1177. */
  1178. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1179. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1180. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1181. }
  1182. return this;
  1183. };
  1184. /**
  1185. * Sets a Color4 on a uniform variable
  1186. * @param uniformName defines the name of the variable
  1187. * @param color4 defines the value to be set
  1188. * @returns this effect.
  1189. */
  1190. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1191. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1192. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1193. }
  1194. return this;
  1195. };
  1196. /**
  1197. * Resets the cache of effects.
  1198. */
  1199. Effect.ResetCache = function () {
  1200. Effect._baseCache = {};
  1201. };
  1202. Effect._uniqueIdSeed = 0;
  1203. Effect._baseCache = {};
  1204. // Statics
  1205. /**
  1206. * Store of each shader (The can be looked up using effect.key)
  1207. */
  1208. Effect.ShadersStore = {};
  1209. /**
  1210. * Store of each included file for a shader (The can be looked up using effect.key)
  1211. */
  1212. Effect.IncludesShadersStore = {};
  1213. return Effect;
  1214. }());
  1215. BABYLON.Effect = Effect;
  1216. })(BABYLON || (BABYLON = {}));
  1217. //# sourceMappingURL=babylon.effect.js.map
  1218. //# sourceMappingURL=babylon.types.js.map
  1219. var BABYLON;
  1220. (function (BABYLON) {
  1221. var KeyboardEventTypes = /** @class */ (function () {
  1222. function KeyboardEventTypes() {
  1223. }
  1224. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1225. get: function () {
  1226. return KeyboardEventTypes._KEYDOWN;
  1227. },
  1228. enumerable: true,
  1229. configurable: true
  1230. });
  1231. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1232. get: function () {
  1233. return KeyboardEventTypes._KEYUP;
  1234. },
  1235. enumerable: true,
  1236. configurable: true
  1237. });
  1238. KeyboardEventTypes._KEYDOWN = 0x01;
  1239. KeyboardEventTypes._KEYUP = 0x02;
  1240. return KeyboardEventTypes;
  1241. }());
  1242. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1243. var KeyboardInfo = /** @class */ (function () {
  1244. function KeyboardInfo(type, event) {
  1245. this.type = type;
  1246. this.event = event;
  1247. }
  1248. return KeyboardInfo;
  1249. }());
  1250. BABYLON.KeyboardInfo = KeyboardInfo;
  1251. /**
  1252. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1253. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1254. */
  1255. var KeyboardInfoPre = /** @class */ (function (_super) {
  1256. __extends(KeyboardInfoPre, _super);
  1257. function KeyboardInfoPre(type, event) {
  1258. var _this = _super.call(this, type, event) || this;
  1259. _this.skipOnPointerObservable = false;
  1260. return _this;
  1261. }
  1262. return KeyboardInfoPre;
  1263. }(KeyboardInfo));
  1264. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1265. })(BABYLON || (BABYLON = {}));
  1266. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1267. var BABYLON;
  1268. (function (BABYLON) {
  1269. var PointerEventTypes = /** @class */ (function () {
  1270. function PointerEventTypes() {
  1271. }
  1272. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1273. get: function () {
  1274. return PointerEventTypes._POINTERDOWN;
  1275. },
  1276. enumerable: true,
  1277. configurable: true
  1278. });
  1279. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1280. get: function () {
  1281. return PointerEventTypes._POINTERUP;
  1282. },
  1283. enumerable: true,
  1284. configurable: true
  1285. });
  1286. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1287. get: function () {
  1288. return PointerEventTypes._POINTERMOVE;
  1289. },
  1290. enumerable: true,
  1291. configurable: true
  1292. });
  1293. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERWHEEL;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERPICK;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERTAP;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERDOUBLETAP;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. PointerEventTypes._POINTERDOWN = 0x01;
  1322. PointerEventTypes._POINTERUP = 0x02;
  1323. PointerEventTypes._POINTERMOVE = 0x04;
  1324. PointerEventTypes._POINTERWHEEL = 0x08;
  1325. PointerEventTypes._POINTERPICK = 0x10;
  1326. PointerEventTypes._POINTERTAP = 0x20;
  1327. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1328. return PointerEventTypes;
  1329. }());
  1330. BABYLON.PointerEventTypes = PointerEventTypes;
  1331. var PointerInfoBase = /** @class */ (function () {
  1332. function PointerInfoBase(type, event) {
  1333. this.type = type;
  1334. this.event = event;
  1335. }
  1336. return PointerInfoBase;
  1337. }());
  1338. BABYLON.PointerInfoBase = PointerInfoBase;
  1339. /**
  1340. * This class is used to store pointer related info for the onPrePointerObservable event.
  1341. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1342. */
  1343. var PointerInfoPre = /** @class */ (function (_super) {
  1344. __extends(PointerInfoPre, _super);
  1345. function PointerInfoPre(type, event, localX, localY) {
  1346. var _this = _super.call(this, type, event) || this;
  1347. _this.skipOnPointerObservable = false;
  1348. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1349. return _this;
  1350. }
  1351. return PointerInfoPre;
  1352. }(PointerInfoBase));
  1353. BABYLON.PointerInfoPre = PointerInfoPre;
  1354. /**
  1355. * This type contains all the data related to a pointer event in Babylon.js.
  1356. * 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.
  1357. */
  1358. var PointerInfo = /** @class */ (function (_super) {
  1359. __extends(PointerInfo, _super);
  1360. function PointerInfo(type, event, pickInfo) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.pickInfo = pickInfo;
  1363. return _this;
  1364. }
  1365. return PointerInfo;
  1366. }(PointerInfoBase));
  1367. BABYLON.PointerInfo = PointerInfo;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.pointerEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. BABYLON.ToGammaSpace = 1 / 2.2;
  1373. BABYLON.ToLinearSpace = 2.2;
  1374. BABYLON.Epsilon = 0.001;
  1375. /**
  1376. * Class used to hold a RBG color
  1377. */
  1378. var Color3 = /** @class */ (function () {
  1379. /**
  1380. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1381. * @param r defines the red component (between 0 and 1, default is 0)
  1382. * @param g defines the green component (between 0 and 1, default is 0)
  1383. * @param b defines the blue component (between 0 and 1, default is 0)
  1384. */
  1385. function Color3(
  1386. /**
  1387. * Defines the red component (between 0 and 1, default is 0)
  1388. */
  1389. r,
  1390. /**
  1391. * Defines the green component (between 0 and 1, default is 0)
  1392. */
  1393. g,
  1394. /**
  1395. * Defines the blue component (between 0 and 1, default is 0)
  1396. */
  1397. b) {
  1398. if (r === void 0) { r = 0; }
  1399. if (g === void 0) { g = 0; }
  1400. if (b === void 0) { b = 0; }
  1401. this.r = r;
  1402. this.g = g;
  1403. this.b = b;
  1404. }
  1405. /**
  1406. * Creates a string with the Color3 current values
  1407. * @returns the string representation of the Color3 object
  1408. */
  1409. Color3.prototype.toString = function () {
  1410. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1411. };
  1412. /**
  1413. * Returns the string "Color3"
  1414. * @returns "Color3"
  1415. */
  1416. Color3.prototype.getClassName = function () {
  1417. return "Color3";
  1418. };
  1419. /**
  1420. * Compute the Color3 hash code
  1421. * @returns an unique number that can be used to hash Color3 objects
  1422. */
  1423. Color3.prototype.getHashCode = function () {
  1424. var hash = this.r || 0;
  1425. hash = (hash * 397) ^ (this.g || 0);
  1426. hash = (hash * 397) ^ (this.b || 0);
  1427. return hash;
  1428. };
  1429. // Operators
  1430. /**
  1431. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1432. * @param array defines the array where to store the r,g,b components
  1433. * @param index defines an optional index in the target array to define where to start storing values
  1434. * @returns the current Color3 object
  1435. */
  1436. Color3.prototype.toArray = function (array, index) {
  1437. if (index === undefined) {
  1438. index = 0;
  1439. }
  1440. array[index] = this.r;
  1441. array[index + 1] = this.g;
  1442. array[index + 2] = this.b;
  1443. return this;
  1444. };
  1445. /**
  1446. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1447. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1448. * @returns a new {BABYLON.Color4} object
  1449. */
  1450. Color3.prototype.toColor4 = function (alpha) {
  1451. if (alpha === void 0) { alpha = 1; }
  1452. return new Color4(this.r, this.g, this.b, alpha);
  1453. };
  1454. /**
  1455. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1456. * @returns the new array
  1457. */
  1458. Color3.prototype.asArray = function () {
  1459. var result = new Array();
  1460. this.toArray(result, 0);
  1461. return result;
  1462. };
  1463. /**
  1464. * Returns the luminance value
  1465. * @returns a float value
  1466. */
  1467. Color3.prototype.toLuminance = function () {
  1468. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1469. };
  1470. /**
  1471. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1472. * @param otherColor defines the second operand
  1473. * @returns the new Color3 object
  1474. */
  1475. Color3.prototype.multiply = function (otherColor) {
  1476. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1477. };
  1478. /**
  1479. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1480. * @param otherColor defines the second operand
  1481. * @param result defines the Color3 object where to store the result
  1482. * @returns the current Color3
  1483. */
  1484. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1485. result.r = this.r * otherColor.r;
  1486. result.g = this.g * otherColor.g;
  1487. result.b = this.b * otherColor.b;
  1488. return this;
  1489. };
  1490. /**
  1491. * Determines equality between Color3 objects
  1492. * @param otherColor defines the second operand
  1493. * @returns true if the rgb values are equal to the passed ones
  1494. */
  1495. Color3.prototype.equals = function (otherColor) {
  1496. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1497. };
  1498. /**
  1499. * Determines equality between the current Color3 object and a set of r,b,g values
  1500. * @param r defines the red component to check
  1501. * @param g defines the green component to check
  1502. * @param b defines the blue component to check
  1503. * @returns true if the rgb values are equal to the passed ones
  1504. */
  1505. Color3.prototype.equalsFloats = function (r, g, b) {
  1506. return this.r === r && this.g === g && this.b === b;
  1507. };
  1508. /**
  1509. * Multiplies in place each rgb value by scale
  1510. * @param scale defines the scaling factor
  1511. * @returns the updated Color3.
  1512. */
  1513. Color3.prototype.scale = function (scale) {
  1514. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1515. };
  1516. /**
  1517. * Multiplies the rgb values by scale and stores the result into "result"
  1518. * @param scale defines the scaling factor
  1519. * @param result defines the Color3 object where to store the result
  1520. * @returns the unmodified current Color3.
  1521. */
  1522. Color3.prototype.scaleToRef = function (scale, result) {
  1523. result.r = this.r * scale;
  1524. result.g = this.g * scale;
  1525. result.b = this.b * scale;
  1526. return this;
  1527. };
  1528. /**
  1529. * Clamps the rgb values by the min and max values and stores the result into "result"
  1530. * @param min defines minimum clamping value (default is 0)
  1531. * @param max defines maximum clamping value (default is 1)
  1532. * @param result defines color to store the result into
  1533. * @returns the original Color3
  1534. */
  1535. Color3.prototype.clampToRef = function (min, max, result) {
  1536. if (min === void 0) { min = 0; }
  1537. if (max === void 0) { max = 1; }
  1538. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1539. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1540. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1541. return this;
  1542. };
  1543. /**
  1544. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1545. * @param otherColor defines the second operand
  1546. * @returns the new Color3
  1547. */
  1548. Color3.prototype.add = function (otherColor) {
  1549. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1550. };
  1551. /**
  1552. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1553. * @param otherColor defines the second operand
  1554. * @param result defines Color3 object to store the result into
  1555. * @returns the unmodified current Color3
  1556. */
  1557. Color3.prototype.addToRef = function (otherColor, result) {
  1558. result.r = this.r + otherColor.r;
  1559. result.g = this.g + otherColor.g;
  1560. result.b = this.b + otherColor.b;
  1561. return this;
  1562. };
  1563. /**
  1564. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1565. * @param otherColor defines the second operand
  1566. * @returns the new Color3
  1567. */
  1568. Color3.prototype.subtract = function (otherColor) {
  1569. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1570. };
  1571. /**
  1572. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1573. * @param otherColor defines the second operand
  1574. * @param result defines Color3 object to store the result into
  1575. * @returns the unmodified current Color3
  1576. */
  1577. Color3.prototype.subtractToRef = function (otherColor, result) {
  1578. result.r = this.r - otherColor.r;
  1579. result.g = this.g - otherColor.g;
  1580. result.b = this.b - otherColor.b;
  1581. return this;
  1582. };
  1583. /**
  1584. * Copy the current object
  1585. * @returns a new Color3 copied the current one
  1586. */
  1587. Color3.prototype.clone = function () {
  1588. return new Color3(this.r, this.g, this.b);
  1589. };
  1590. /**
  1591. * Copies the rgb values from the source in the current Color3
  1592. * @param source defines the source Color3 object
  1593. * @returns the updated Color3 object
  1594. */
  1595. Color3.prototype.copyFrom = function (source) {
  1596. this.r = source.r;
  1597. this.g = source.g;
  1598. this.b = source.b;
  1599. return this;
  1600. };
  1601. /**
  1602. * Updates the Color3 rgb values from the passed floats
  1603. * @param r defines the red component to read from
  1604. * @param g defines the green component to read from
  1605. * @param b defines the blue component to read from
  1606. * @returns the current Color3 object
  1607. */
  1608. Color3.prototype.copyFromFloats = function (r, g, b) {
  1609. this.r = r;
  1610. this.g = g;
  1611. this.b = b;
  1612. return this;
  1613. };
  1614. /**
  1615. * Updates the Color3 rgb values from the passed floats
  1616. * @param r defines the red component to read from
  1617. * @param g defines the green component to read from
  1618. * @param b defines the blue component to read from
  1619. * @returns the current Color3 object
  1620. */
  1621. Color3.prototype.set = function (r, g, b) {
  1622. return this.copyFromFloats(r, g, b);
  1623. };
  1624. /**
  1625. * Compute the Color3 hexadecimal code as a string
  1626. * @returns a string containing the hexadecimal representation of the Color3 object
  1627. */
  1628. Color3.prototype.toHexString = function () {
  1629. var intR = (this.r * 255) | 0;
  1630. var intG = (this.g * 255) | 0;
  1631. var intB = (this.b * 255) | 0;
  1632. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1633. };
  1634. /**
  1635. * Computes a new Color3 converted from the current one to linear space
  1636. * @returns a new Color3 object
  1637. */
  1638. Color3.prototype.toLinearSpace = function () {
  1639. var convertedColor = new Color3();
  1640. this.toLinearSpaceToRef(convertedColor);
  1641. return convertedColor;
  1642. };
  1643. /**
  1644. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1645. * @param convertedColor defines the Color3 object where to store the linear space version
  1646. * @returns the unmodified Color3
  1647. */
  1648. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1649. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1650. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1651. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1652. return this;
  1653. };
  1654. /**
  1655. * Computes a new Color3 converted from the current one to gamma space
  1656. * @returns a new Color3 object
  1657. */
  1658. Color3.prototype.toGammaSpace = function () {
  1659. var convertedColor = new Color3();
  1660. this.toGammaSpaceToRef(convertedColor);
  1661. return convertedColor;
  1662. };
  1663. /**
  1664. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1665. * @param convertedColor defines the Color3 object where to store the gamma space version
  1666. * @returns the unmodified Color3
  1667. */
  1668. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1669. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1670. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1671. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1672. return this;
  1673. };
  1674. // Statics
  1675. /**
  1676. * Creates a new Color3 from the string containing valid hexadecimal values
  1677. * @param hex defines a string containing valid hexadecimal values
  1678. * @returns a new Color3 object
  1679. */
  1680. Color3.FromHexString = function (hex) {
  1681. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1682. return new Color3(0, 0, 0);
  1683. }
  1684. var r = parseInt(hex.substring(1, 3), 16);
  1685. var g = parseInt(hex.substring(3, 5), 16);
  1686. var b = parseInt(hex.substring(5, 7), 16);
  1687. return Color3.FromInts(r, g, b);
  1688. };
  1689. /**
  1690. * Creates a new Vector3 from the starting index of the passed array
  1691. * @param array defines the source array
  1692. * @param offset defines an offset in the source array
  1693. * @returns a new Color3 object
  1694. */
  1695. Color3.FromArray = function (array, offset) {
  1696. if (offset === void 0) { offset = 0; }
  1697. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1698. };
  1699. /**
  1700. * Creates a new Color3 from integer values (< 256)
  1701. * @param r defines the red component to read from (value between 0 and 255)
  1702. * @param g defines the green component to read from (value between 0 and 255)
  1703. * @param b defines the blue component to read from (value between 0 and 255)
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.FromInts = function (r, g, b) {
  1707. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1708. };
  1709. /**
  1710. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1711. * @param start defines the start Color3 value
  1712. * @param end defines the end Color3 value
  1713. * @param amount defines the gradient value between start and end
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Lerp = function (start, end, amount) {
  1717. var r = start.r + ((end.r - start.r) * amount);
  1718. var g = start.g + ((end.g - start.g) * amount);
  1719. var b = start.b + ((end.b - start.b) * amount);
  1720. return new Color3(r, g, b);
  1721. };
  1722. /**
  1723. * Returns a Color3 value containing a red color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Red = function () { return new Color3(1, 0, 0); };
  1727. /**
  1728. * Returns a Color3 value containing a green color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Green = function () { return new Color3(0, 1, 0); };
  1732. /**
  1733. * Returns a Color3 value containing a blue color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1737. /**
  1738. * Returns a Color3 value containing a black color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Black = function () { return new Color3(0, 0, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a white color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.White = function () { return new Color3(1, 1, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a purple color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1752. /**
  1753. * Returns a Color3 value containing a magenta color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a yellow color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a gray color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1767. /**
  1768. * Returns a Color3 value containing a teal color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1772. /**
  1773. * Returns a Color3 value containing a random color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1777. return Color3;
  1778. }());
  1779. BABYLON.Color3 = Color3;
  1780. /**
  1781. * Class used to hold a RBGA color
  1782. */
  1783. var Color4 = /** @class */ (function () {
  1784. /**
  1785. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1786. * @param r defines the red component (between 0 and 1, default is 0)
  1787. * @param g defines the green component (between 0 and 1, default is 0)
  1788. * @param b defines the blue component (between 0 and 1, default is 0)
  1789. * @param a defines the alpha component (between 0 and 1, default is 1)
  1790. */
  1791. function Color4(
  1792. /**
  1793. * Defines the red component (between 0 and 1, default is 0)
  1794. */
  1795. r,
  1796. /**
  1797. * Defines the green component (between 0 and 1, default is 0)
  1798. */
  1799. g,
  1800. /**
  1801. * Defines the blue component (between 0 and 1, default is 0)
  1802. */
  1803. b,
  1804. /**
  1805. * Defines the alpha component (between 0 and 1, default is 1)
  1806. */
  1807. a) {
  1808. if (r === void 0) { r = 0; }
  1809. if (g === void 0) { g = 0; }
  1810. if (b === void 0) { b = 0; }
  1811. if (a === void 0) { a = 1; }
  1812. this.r = r;
  1813. this.g = g;
  1814. this.b = b;
  1815. this.a = a;
  1816. }
  1817. // Operators
  1818. /**
  1819. * Adds in place the passed Color4 values to the current Color4 object
  1820. * @param right defines the second operand
  1821. * @returns the current updated Color4 object
  1822. */
  1823. Color4.prototype.addInPlace = function (right) {
  1824. this.r += right.r;
  1825. this.g += right.g;
  1826. this.b += right.b;
  1827. this.a += right.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1832. * @returns the new array
  1833. */
  1834. Color4.prototype.asArray = function () {
  1835. var result = new Array();
  1836. this.toArray(result, 0);
  1837. return result;
  1838. };
  1839. /**
  1840. * Stores from the starting index in the passed array the Color4 successive values
  1841. * @param array defines the array where to store the r,g,b components
  1842. * @param index defines an optional index in the target array to define where to start storing values
  1843. * @returns the current Color4 object
  1844. */
  1845. Color4.prototype.toArray = function (array, index) {
  1846. if (index === undefined) {
  1847. index = 0;
  1848. }
  1849. array[index] = this.r;
  1850. array[index + 1] = this.g;
  1851. array[index + 2] = this.b;
  1852. array[index + 3] = this.a;
  1853. return this;
  1854. };
  1855. /**
  1856. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1857. * @param right defines the second operand
  1858. * @returns a new Color4 object
  1859. */
  1860. Color4.prototype.add = function (right) {
  1861. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.subtract = function (right) {
  1869. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1870. };
  1871. /**
  1872. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1873. * @param right defines the second operand
  1874. * @param result defines the Color4 object where to store the result
  1875. * @returns the current Color4 object
  1876. */
  1877. Color4.prototype.subtractToRef = function (right, result) {
  1878. result.r = this.r - right.r;
  1879. result.g = this.g - right.g;
  1880. result.b = this.b - right.b;
  1881. result.a = this.a - right.a;
  1882. return this;
  1883. };
  1884. /**
  1885. * Creates a new Color4 with the current Color4 values multiplied by scale
  1886. * @param scale defines the scaling factor to apply
  1887. * @returns a new Color4 object
  1888. */
  1889. Color4.prototype.scale = function (scale) {
  1890. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1891. };
  1892. /**
  1893. * Multiplies the current Color4 values by scale and stores the result in "result"
  1894. * @param scale defines the scaling factor to apply
  1895. * @param result defines the Color4 object where to store the result
  1896. * @returns the current Color4.
  1897. */
  1898. Color4.prototype.scaleToRef = function (scale, result) {
  1899. result.r = this.r * scale;
  1900. result.g = this.g * scale;
  1901. result.b = this.b * scale;
  1902. result.a = this.a * scale;
  1903. return this;
  1904. };
  1905. /**
  1906. * Clamps the rgb values by the min and max values and stores the result into "result"
  1907. * @param min defines minimum clamping value (default is 0)
  1908. * @param max defines maximum clamping value (default is 1)
  1909. * @param result defines color to store the result into.
  1910. * @returns the cuurent Color4
  1911. */
  1912. Color4.prototype.clampToRef = function (min, max, result) {
  1913. if (min === void 0) { min = 0; }
  1914. if (max === void 0) { max = 1; }
  1915. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1916. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1917. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1918. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1919. return this;
  1920. };
  1921. /**
  1922. * Multipy an Color4 value by another and return a new Color4 object
  1923. * @param color defines the Color4 value to multiply by
  1924. * @returns a new Color4 object
  1925. */
  1926. Color4.prototype.multiply = function (color) {
  1927. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1928. };
  1929. /**
  1930. * Multipy a Color4 value by another and push the result in a reference value
  1931. * @param color defines the Color4 value to multiply by
  1932. * @param result defines the Color4 to fill the result in
  1933. * @returns the result Color4
  1934. */
  1935. Color4.prototype.multiplyToRef = function (color, result) {
  1936. result.r = this.r * color.r;
  1937. result.g = this.g * color.g;
  1938. result.b = this.b * color.b;
  1939. result.a = this.a * color.a;
  1940. return result;
  1941. };
  1942. /**
  1943. * Creates a string with the Color4 current values
  1944. * @returns the string representation of the Color4 object
  1945. */
  1946. Color4.prototype.toString = function () {
  1947. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1948. };
  1949. /**
  1950. * Returns the string "Color4"
  1951. * @returns "Color4"
  1952. */
  1953. Color4.prototype.getClassName = function () {
  1954. return "Color4";
  1955. };
  1956. /**
  1957. * Compute the Color4 hash code
  1958. * @returns an unique number that can be used to hash Color4 objects
  1959. */
  1960. Color4.prototype.getHashCode = function () {
  1961. var hash = this.r || 0;
  1962. hash = (hash * 397) ^ (this.g || 0);
  1963. hash = (hash * 397) ^ (this.b || 0);
  1964. hash = (hash * 397) ^ (this.a || 0);
  1965. return hash;
  1966. };
  1967. /**
  1968. * Creates a new Color4 copied from the current one
  1969. * @returns a new Color4 object
  1970. */
  1971. Color4.prototype.clone = function () {
  1972. return new Color4(this.r, this.g, this.b, this.a);
  1973. };
  1974. /**
  1975. * Copies the passed Color4 values into the current one
  1976. * @param source defines the source Color4 object
  1977. * @returns the current updated Color4 object
  1978. */
  1979. Color4.prototype.copyFrom = function (source) {
  1980. this.r = source.r;
  1981. this.g = source.g;
  1982. this.b = source.b;
  1983. this.a = source.a;
  1984. return this;
  1985. };
  1986. /**
  1987. * Copies the passed float values into the current one
  1988. * @param r defines the red component to read from
  1989. * @param g defines the green component to read from
  1990. * @param b defines the blue component to read from
  1991. * @param a defines the alpha component to read from
  1992. * @returns the current updated Color4 object
  1993. */
  1994. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1995. this.r = r;
  1996. this.g = g;
  1997. this.b = b;
  1998. this.a = a;
  1999. return this;
  2000. };
  2001. /**
  2002. * Copies the passed float values into the current one
  2003. * @param r defines the red component to read from
  2004. * @param g defines the green component to read from
  2005. * @param b defines the blue component to read from
  2006. * @param a defines the alpha component to read from
  2007. * @returns the current updated Color4 object
  2008. */
  2009. Color4.prototype.set = function (r, g, b, a) {
  2010. return this.copyFromFloats(r, g, b, a);
  2011. };
  2012. /**
  2013. * Compute the Color4 hexadecimal code as a string
  2014. * @returns a string containing the hexadecimal representation of the Color4 object
  2015. */
  2016. Color4.prototype.toHexString = function () {
  2017. var intR = (this.r * 255) | 0;
  2018. var intG = (this.g * 255) | 0;
  2019. var intB = (this.b * 255) | 0;
  2020. var intA = (this.a * 255) | 0;
  2021. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2022. };
  2023. /**
  2024. * Computes a new Color4 converted from the current one to linear space
  2025. * @returns a new Color4 object
  2026. */
  2027. Color4.prototype.toLinearSpace = function () {
  2028. var convertedColor = new Color4();
  2029. this.toLinearSpaceToRef(convertedColor);
  2030. return convertedColor;
  2031. };
  2032. /**
  2033. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2034. * @param convertedColor defines the Color4 object where to store the linear space version
  2035. * @returns the unmodified Color4
  2036. */
  2037. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2038. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2039. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2040. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2041. convertedColor.a = this.a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to gamma space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toGammaSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toGammaSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the gamma space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. // Statics
  2066. /**
  2067. * Creates a new Color4 from the string containing valid hexadecimal values
  2068. * @param hex defines a string containing valid hexadecimal values
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.FromHexString = function (hex) {
  2072. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2073. return new Color4(0.0, 0.0, 0.0, 0.0);
  2074. }
  2075. var r = parseInt(hex.substring(1, 3), 16);
  2076. var g = parseInt(hex.substring(3, 5), 16);
  2077. var b = parseInt(hex.substring(5, 7), 16);
  2078. var a = parseInt(hex.substring(7, 9), 16);
  2079. return Color4.FromInts(r, g, b, a);
  2080. };
  2081. /**
  2082. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2083. * @param left defines the start value
  2084. * @param right defines the end value
  2085. * @param amount defines the gradient factor
  2086. * @returns a new Color4 object
  2087. */
  2088. Color4.Lerp = function (left, right, amount) {
  2089. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2090. Color4.LerpToRef(left, right, amount, result);
  2091. return result;
  2092. };
  2093. /**
  2094. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2095. * @param left defines the start value
  2096. * @param right defines the end value
  2097. * @param amount defines the gradient factor
  2098. * @param result defines the Color4 object where to store data
  2099. */
  2100. Color4.LerpToRef = function (left, right, amount, result) {
  2101. result.r = left.r + (right.r - left.r) * amount;
  2102. result.g = left.g + (right.g - left.g) * amount;
  2103. result.b = left.b + (right.b - left.b) * amount;
  2104. result.a = left.a + (right.a - left.a) * amount;
  2105. };
  2106. /**
  2107. * Creates a new Color4 from the starting index element of the passed array
  2108. * @param array defines the source array to read from
  2109. * @param offset defines the offset in the source array
  2110. * @returns a new Color4 object
  2111. */
  2112. Color4.FromArray = function (array, offset) {
  2113. if (offset === void 0) { offset = 0; }
  2114. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2115. };
  2116. /**
  2117. * Creates a new Color3 from integer values (< 256)
  2118. * @param r defines the red component to read from (value between 0 and 255)
  2119. * @param g defines the green component to read from (value between 0 and 255)
  2120. * @param b defines the blue component to read from (value between 0 and 255)
  2121. * @param a defines the alpha component to read from (value between 0 and 255)
  2122. * @returns a new Color3 object
  2123. */
  2124. Color4.FromInts = function (r, g, b, a) {
  2125. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2126. };
  2127. /**
  2128. * Check the content of a given array and convert it to an array containing RGBA data
  2129. * If the original array was already containing count * 4 values then it is returned directly
  2130. * @param colors defines the array to check
  2131. * @param count defines the number of RGBA data to expect
  2132. * @returns an array containing count * 4 values (RGBA)
  2133. */
  2134. Color4.CheckColors4 = function (colors, count) {
  2135. // Check if color3 was used
  2136. if (colors.length === count * 3) {
  2137. var colors4 = [];
  2138. for (var index = 0; index < colors.length; index += 3) {
  2139. var newIndex = (index / 3) * 4;
  2140. colors4[newIndex] = colors[index];
  2141. colors4[newIndex + 1] = colors[index + 1];
  2142. colors4[newIndex + 2] = colors[index + 2];
  2143. colors4[newIndex + 3] = 1.0;
  2144. }
  2145. return colors4;
  2146. }
  2147. return colors;
  2148. };
  2149. return Color4;
  2150. }());
  2151. BABYLON.Color4 = Color4;
  2152. var Vector2 = /** @class */ (function () {
  2153. /**
  2154. * Creates a new Vector2 from the passed x and y coordinates.
  2155. */
  2156. function Vector2(x, y) {
  2157. this.x = x;
  2158. this.y = y;
  2159. }
  2160. /**
  2161. * Returns a string with the Vector2 coordinates.
  2162. */
  2163. Vector2.prototype.toString = function () {
  2164. return "{X: " + this.x + " Y:" + this.y + "}";
  2165. };
  2166. /**
  2167. * Returns the string "Vector2"
  2168. */
  2169. Vector2.prototype.getClassName = function () {
  2170. return "Vector2";
  2171. };
  2172. /**
  2173. * Returns the Vector2 hash code as a number.
  2174. */
  2175. Vector2.prototype.getHashCode = function () {
  2176. var hash = this.x || 0;
  2177. hash = (hash * 397) ^ (this.y || 0);
  2178. return hash;
  2179. };
  2180. // Operators
  2181. /**
  2182. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2183. * Returns the Vector2.
  2184. */
  2185. Vector2.prototype.toArray = function (array, index) {
  2186. if (index === void 0) { index = 0; }
  2187. array[index] = this.x;
  2188. array[index + 1] = this.y;
  2189. return this;
  2190. };
  2191. /**
  2192. * Returns a new array with 2 elements : the Vector2 coordinates.
  2193. */
  2194. Vector2.prototype.asArray = function () {
  2195. var result = new Array();
  2196. this.toArray(result, 0);
  2197. return result;
  2198. };
  2199. /**
  2200. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2201. * Returns the updated Vector2.
  2202. */
  2203. Vector2.prototype.copyFrom = function (source) {
  2204. this.x = source.x;
  2205. this.y = source.y;
  2206. return this;
  2207. };
  2208. /**
  2209. * Sets the Vector2 coordinates with the passed floats.
  2210. * Returns the updated Vector2.
  2211. */
  2212. Vector2.prototype.copyFromFloats = function (x, y) {
  2213. this.x = x;
  2214. this.y = y;
  2215. return this;
  2216. };
  2217. /**
  2218. * Sets the Vector2 coordinates with the passed floats.
  2219. * Returns the updated Vector2.
  2220. */
  2221. Vector2.prototype.set = function (x, y) {
  2222. return this.copyFromFloats(x, y);
  2223. };
  2224. /**
  2225. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2226. */
  2227. Vector2.prototype.add = function (otherVector) {
  2228. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2229. };
  2230. /**
  2231. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2232. * Returns the Vector2.
  2233. */
  2234. Vector2.prototype.addToRef = function (otherVector, result) {
  2235. result.x = this.x + otherVector.x;
  2236. result.y = this.y + otherVector.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2241. * Returns the updated Vector2.
  2242. */
  2243. Vector2.prototype.addInPlace = function (otherVector) {
  2244. this.x += otherVector.x;
  2245. this.y += otherVector.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2250. */
  2251. Vector2.prototype.addVector3 = function (otherVector) {
  2252. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2253. };
  2254. /**
  2255. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2256. */
  2257. Vector2.prototype.subtract = function (otherVector) {
  2258. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2259. };
  2260. /**
  2261. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2262. * Returns the Vector2.
  2263. */
  2264. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2265. result.x = this.x - otherVector.x;
  2266. result.y = this.y - otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2271. * Returns the updated Vector2.
  2272. */
  2273. Vector2.prototype.subtractInPlace = function (otherVector) {
  2274. this.x -= otherVector.x;
  2275. this.y -= otherVector.y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2280. * Returns the updated Vector2.
  2281. */
  2282. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2283. this.x *= otherVector.x;
  2284. this.y *= otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2289. */
  2290. Vector2.prototype.multiply = function (otherVector) {
  2291. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2292. };
  2293. /**
  2294. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2295. * Returns the Vector2.
  2296. */
  2297. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2298. result.x = this.x * otherVector.x;
  2299. result.y = this.y * otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2304. */
  2305. Vector2.prototype.multiplyByFloats = function (x, y) {
  2306. return new Vector2(this.x * x, this.y * y);
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2310. */
  2311. Vector2.prototype.divide = function (otherVector) {
  2312. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.divideToRef = function (otherVector, result) {
  2319. result.x = this.x / otherVector.x;
  2320. result.y = this.y / otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Divides the current Vector3 coordinates by the passed ones.
  2325. * Returns the updated Vector3.
  2326. */
  2327. Vector2.prototype.divideInPlace = function (otherVector) {
  2328. return this.divideToRef(otherVector, this);
  2329. };
  2330. /**
  2331. * Returns a new Vector2 with current Vector2 negated coordinates.
  2332. */
  2333. Vector2.prototype.negate = function () {
  2334. return new Vector2(-this.x, -this.y);
  2335. };
  2336. /**
  2337. * Multiply the Vector2 coordinates by scale.
  2338. * Returns the updated Vector2.
  2339. */
  2340. Vector2.prototype.scaleInPlace = function (scale) {
  2341. this.x *= scale;
  2342. this.y *= scale;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2347. */
  2348. Vector2.prototype.scale = function (scale) {
  2349. return new Vector2(this.x * scale, this.y * scale);
  2350. };
  2351. /**
  2352. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2353. */
  2354. Vector2.prototype.equals = function (otherVector) {
  2355. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2356. };
  2357. /**
  2358. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2359. */
  2360. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2361. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2362. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2363. };
  2364. // Properties
  2365. /**
  2366. * Returns the vector length (float).
  2367. */
  2368. Vector2.prototype.length = function () {
  2369. return Math.sqrt(this.x * this.x + this.y * this.y);
  2370. };
  2371. /**
  2372. * Returns the vector squared length (float);
  2373. */
  2374. Vector2.prototype.lengthSquared = function () {
  2375. return (this.x * this.x + this.y * this.y);
  2376. };
  2377. // Methods
  2378. /**
  2379. * Normalize the vector.
  2380. * Returns the updated Vector2.
  2381. */
  2382. Vector2.prototype.normalize = function () {
  2383. var len = this.length();
  2384. if (len === 0)
  2385. return this;
  2386. var num = 1.0 / len;
  2387. this.x *= num;
  2388. this.y *= num;
  2389. return this;
  2390. };
  2391. /**
  2392. * Returns a new Vector2 copied from the Vector2.
  2393. */
  2394. Vector2.prototype.clone = function () {
  2395. return new Vector2(this.x, this.y);
  2396. };
  2397. // Statics
  2398. /**
  2399. * Returns a new Vector2(0, 0)
  2400. */
  2401. Vector2.Zero = function () {
  2402. return new Vector2(0, 0);
  2403. };
  2404. /**
  2405. * Returns a new Vector2(1, 1)
  2406. */
  2407. Vector2.One = function () {
  2408. return new Vector2(1, 1);
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set from the passed index element of the passed array.
  2412. */
  2413. Vector2.FromArray = function (array, offset) {
  2414. if (offset === void 0) { offset = 0; }
  2415. return new Vector2(array[offset], array[offset + 1]);
  2416. };
  2417. /**
  2418. * Sets "result" from the passed index element of the passed array.
  2419. */
  2420. Vector2.FromArrayToRef = function (array, offset, result) {
  2421. result.x = array[offset];
  2422. result.y = array[offset + 1];
  2423. };
  2424. /**
  2425. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2426. */
  2427. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2428. var squared = amount * amount;
  2429. var cubed = amount * squared;
  2430. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2431. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2432. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2433. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2434. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2435. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2436. return new Vector2(x, y);
  2437. };
  2438. /**
  2439. * 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".
  2440. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2441. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2442. */
  2443. Vector2.Clamp = function (value, min, max) {
  2444. var x = value.x;
  2445. x = (x > max.x) ? max.x : x;
  2446. x = (x < min.x) ? min.x : x;
  2447. var y = value.y;
  2448. y = (y > max.y) ? max.y : y;
  2449. y = (y < min.y) ? min.y : y;
  2450. return new Vector2(x, y);
  2451. };
  2452. /**
  2453. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2454. */
  2455. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2456. var squared = amount * amount;
  2457. var cubed = amount * squared;
  2458. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2459. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2460. var part3 = (cubed - (2.0 * squared)) + amount;
  2461. var part4 = cubed - squared;
  2462. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2463. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2464. return new Vector2(x, y);
  2465. };
  2466. /**
  2467. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2468. */
  2469. Vector2.Lerp = function (start, end, amount) {
  2470. var x = start.x + ((end.x - start.x) * amount);
  2471. var y = start.y + ((end.y - start.y) * amount);
  2472. return new Vector2(x, y);
  2473. };
  2474. /**
  2475. * Returns the dot product (float) of the vector "left" and the vector "right".
  2476. */
  2477. Vector2.Dot = function (left, right) {
  2478. return left.x * right.x + left.y * right.y;
  2479. };
  2480. /**
  2481. * Returns a new Vector2 equal to the normalized passed vector.
  2482. */
  2483. Vector2.Normalize = function (vector) {
  2484. var newVector = vector.clone();
  2485. newVector.normalize();
  2486. return newVector;
  2487. };
  2488. /**
  2489. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2490. */
  2491. Vector2.Minimize = function (left, right) {
  2492. var x = (left.x < right.x) ? left.x : right.x;
  2493. var y = (left.y < right.y) ? left.y : right.y;
  2494. return new Vector2(x, y);
  2495. };
  2496. /**
  2497. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2498. */
  2499. Vector2.Maximize = function (left, right) {
  2500. var x = (left.x > right.x) ? left.x : right.x;
  2501. var y = (left.y > right.y) ? left.y : right.y;
  2502. return new Vector2(x, y);
  2503. };
  2504. /**
  2505. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2506. */
  2507. Vector2.Transform = function (vector, transformation) {
  2508. var r = Vector2.Zero();
  2509. Vector2.TransformToRef(vector, transformation, r);
  2510. return r;
  2511. };
  2512. /**
  2513. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2514. */
  2515. Vector2.TransformToRef = function (vector, transformation, result) {
  2516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2518. result.x = x;
  2519. result.y = y;
  2520. };
  2521. /**
  2522. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2523. */
  2524. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2525. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2526. var sign = a < 0 ? -1 : 1;
  2527. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2528. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2529. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2530. };
  2531. /**
  2532. * Returns the distance (float) between the vectors "value1" and "value2".
  2533. */
  2534. Vector2.Distance = function (value1, value2) {
  2535. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2536. };
  2537. /**
  2538. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2539. */
  2540. Vector2.DistanceSquared = function (value1, value2) {
  2541. var x = value1.x - value2.x;
  2542. var y = value1.y - value2.y;
  2543. return (x * x) + (y * y);
  2544. };
  2545. /**
  2546. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2547. */
  2548. Vector2.Center = function (value1, value2) {
  2549. var center = value1.add(value2);
  2550. center.scaleInPlace(0.5);
  2551. return center;
  2552. };
  2553. /**
  2554. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2555. */
  2556. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2557. var l2 = Vector2.DistanceSquared(segA, segB);
  2558. if (l2 === 0.0) {
  2559. return Vector2.Distance(p, segA);
  2560. }
  2561. var v = segB.subtract(segA);
  2562. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2563. var proj = segA.add(v.multiplyByFloats(t, t));
  2564. return Vector2.Distance(p, proj);
  2565. };
  2566. return Vector2;
  2567. }());
  2568. BABYLON.Vector2 = Vector2;
  2569. /**
  2570. * Classed used to store (x,y,z) vector representation
  2571. * A Vector3 is the main object used in 3D geometry
  2572. * It can represent etiher the coordinates of a point the space, either a direction
  2573. * Reminder: Babylon.js uses a left handed forward facing system
  2574. */
  2575. var Vector3 = /** @class */ (function () {
  2576. /**
  2577. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2578. * @param x defines the first coordinates (on X axis)
  2579. * @param y defines the second coordinates (on Y axis)
  2580. * @param z defines the third coordinates (on Z axis)
  2581. */
  2582. function Vector3(
  2583. /**
  2584. * Defines the first coordinates (on X axis)
  2585. */
  2586. x,
  2587. /**
  2588. * Defines the second coordinates (on Y axis)
  2589. */
  2590. y,
  2591. /**
  2592. * Defines the third coordinates (on Z axis)
  2593. */
  2594. z) {
  2595. this.x = x;
  2596. this.y = y;
  2597. this.z = z;
  2598. }
  2599. /**
  2600. * Creates a string representation of the Vector3
  2601. * @returns a string with the Vector3 coordinates.
  2602. */
  2603. Vector3.prototype.toString = function () {
  2604. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2605. };
  2606. /**
  2607. * Gets the class name
  2608. * @returns the string "Vector3"
  2609. */
  2610. Vector3.prototype.getClassName = function () {
  2611. return "Vector3";
  2612. };
  2613. /**
  2614. * Creates the Vector3 hash code
  2615. * @returns a number which tends to be unique between Vector3 instances
  2616. */
  2617. Vector3.prototype.getHashCode = function () {
  2618. var hash = this.x || 0;
  2619. hash = (hash * 397) ^ (this.y || 0);
  2620. hash = (hash * 397) ^ (this.z || 0);
  2621. return hash;
  2622. };
  2623. // Operators
  2624. /**
  2625. * Creates an array containing three elements : the coordinates of the Vector3
  2626. * @returns a new array of numbers
  2627. */
  2628. Vector3.prototype.asArray = function () {
  2629. var result = [];
  2630. this.toArray(result, 0);
  2631. return result;
  2632. };
  2633. /**
  2634. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2635. * @param array defines the destination array
  2636. * @param index defines the offset in the destination array
  2637. * @returns the current Vector3
  2638. */
  2639. Vector3.prototype.toArray = function (array, index) {
  2640. if (index === void 0) { index = 0; }
  2641. array[index] = this.x;
  2642. array[index + 1] = this.y;
  2643. array[index + 2] = this.z;
  2644. return this;
  2645. };
  2646. /**
  2647. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2648. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2649. */
  2650. Vector3.prototype.toQuaternion = function () {
  2651. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2652. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2653. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2654. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2655. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2656. var cosy = Math.cos(this.y * 0.5);
  2657. var siny = Math.sin(this.y * 0.5);
  2658. result.x = coszMinusx * siny;
  2659. result.y = -sinzMinusx * siny;
  2660. result.z = sinxPlusz * cosy;
  2661. result.w = cosxPlusz * cosy;
  2662. return result;
  2663. };
  2664. /**
  2665. * Adds the passed vector to the current Vector3
  2666. * @param otherVector defines the second operand
  2667. * @returns the current updated Vector3
  2668. */
  2669. Vector3.prototype.addInPlace = function (otherVector) {
  2670. this.x += otherVector.x;
  2671. this.y += otherVector.y;
  2672. this.z += otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2677. * @param otherVector defines the second operand
  2678. * @returns the resulting Vector3
  2679. */
  2680. Vector3.prototype.add = function (otherVector) {
  2681. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2682. };
  2683. /**
  2684. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2685. * @param otherVector defines the second operand
  2686. * @param result defines the Vector3 object where to store the result
  2687. * @returns the current Vector3
  2688. */
  2689. Vector3.prototype.addToRef = function (otherVector, result) {
  2690. result.x = this.x + otherVector.x;
  2691. result.y = this.y + otherVector.y;
  2692. result.z = this.z + otherVector.z;
  2693. return this;
  2694. };
  2695. /**
  2696. * Subtract the passed vector from the current Vector3
  2697. * @param otherVector defines the second operand
  2698. * @returns the current updated Vector3
  2699. */
  2700. Vector3.prototype.subtractInPlace = function (otherVector) {
  2701. this.x -= otherVector.x;
  2702. this.y -= otherVector.y;
  2703. this.z -= otherVector.z;
  2704. return this;
  2705. };
  2706. /**
  2707. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2708. * @param otherVector defines the second operand
  2709. * @returns the resulting Vector3
  2710. */
  2711. Vector3.prototype.subtract = function (otherVector) {
  2712. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2713. };
  2714. /**
  2715. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2716. * @param otherVector defines the second operand
  2717. * @param result defines the Vector3 object where to store the result
  2718. * @returns the current Vector3
  2719. */
  2720. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2721. result.x = this.x - otherVector.x;
  2722. result.y = this.y - otherVector.y;
  2723. result.z = this.z - otherVector.z;
  2724. return this;
  2725. };
  2726. /**
  2727. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2728. * @param x defines the x coordinate of the operand
  2729. * @param y defines the y coordinate of the operand
  2730. * @param z defines the z coordinate of the operand
  2731. * @returns the resulting Vector3
  2732. */
  2733. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2734. return new Vector3(this.x - x, this.y - y, this.z - z);
  2735. };
  2736. /**
  2737. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2738. * @param x defines the x coordinate of the operand
  2739. * @param y defines the y coordinate of the operand
  2740. * @param z defines the z coordinate of the operand
  2741. * @param result defines the Vector3 object where to store the result
  2742. * @returns the current Vector3
  2743. */
  2744. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2745. result.x = this.x - x;
  2746. result.y = this.y - y;
  2747. result.z = this.z - z;
  2748. return this;
  2749. };
  2750. /**
  2751. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2752. * @returns a new Vector3
  2753. */
  2754. Vector3.prototype.negate = function () {
  2755. return new Vector3(-this.x, -this.y, -this.z);
  2756. };
  2757. /**
  2758. * Multiplies the Vector3 coordinates by the float "scale"
  2759. * @param scale defines the multiplier factor
  2760. * @returns the current updated Vector3
  2761. */
  2762. Vector3.prototype.scaleInPlace = function (scale) {
  2763. this.x *= scale;
  2764. this.y *= scale;
  2765. this.z *= scale;
  2766. return this;
  2767. };
  2768. /**
  2769. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2770. * @param scale defines the multiplier factor
  2771. * @returns a new Vector3
  2772. */
  2773. Vector3.prototype.scale = function (scale) {
  2774. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2775. };
  2776. /**
  2777. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2778. * @param scale defines the multiplier factor
  2779. * @param result defines the Vector3 object where to store the result
  2780. * @returns the current Vector3
  2781. */
  2782. Vector3.prototype.scaleToRef = function (scale, result) {
  2783. result.x = this.x * scale;
  2784. result.y = this.y * scale;
  2785. result.z = this.z * scale;
  2786. return this;
  2787. };
  2788. /**
  2789. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2790. * @param otherVector defines the second operand
  2791. * @returns true if both vectors are equals
  2792. */
  2793. Vector3.prototype.equals = function (otherVector) {
  2794. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2795. };
  2796. /**
  2797. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2798. * @param otherVector defines the second operand
  2799. * @param epsilon defines the minimal distance to define values as equals
  2800. * @returns true if both vectors are distant less than epsilon
  2801. */
  2802. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2803. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2804. 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);
  2805. };
  2806. /**
  2807. * Returns true if the current Vector3 coordinates equals the passed floats
  2808. * @param x defines the x coordinate of the operand
  2809. * @param y defines the y coordinate of the operand
  2810. * @param z defines the z coordinate of the operand
  2811. * @returns true if both vectors are equals
  2812. */
  2813. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2814. return this.x === x && this.y === y && this.z === z;
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the passed ones
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2822. this.x *= otherVector.x;
  2823. this.y *= otherVector.y;
  2824. this.z *= otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the new Vector3
  2831. */
  2832. Vector3.prototype.multiply = function (otherVector) {
  2833. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2834. };
  2835. /**
  2836. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2842. result.x = this.x * otherVector.x;
  2843. result.y = this.y * otherVector.y;
  2844. result.z = this.z * otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2849. * @param x defines the x coordinate of the operand
  2850. * @param y defines the y coordinate of the operand
  2851. * @param z defines the z coordinate of the operand
  2852. * @returns the new Vector3
  2853. */
  2854. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2855. return new Vector3(this.x * x, this.y * y, this.z * z);
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2859. * @param otherVector defines the second operand
  2860. * @returns the new Vector3
  2861. */
  2862. Vector3.prototype.divide = function (otherVector) {
  2863. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2864. };
  2865. /**
  2866. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2867. * @param otherVector defines the second operand
  2868. * @param result defines the Vector3 object where to store the result
  2869. * @returns the current Vector3
  2870. */
  2871. Vector3.prototype.divideToRef = function (otherVector, result) {
  2872. result.x = this.x / otherVector.x;
  2873. result.y = this.y / otherVector.y;
  2874. result.z = this.z / otherVector.z;
  2875. return this;
  2876. };
  2877. /**
  2878. * Divides the current Vector3 coordinates by the passed ones.
  2879. * @param otherVector defines the second operand
  2880. * @returns the current updated Vector3
  2881. */
  2882. Vector3.prototype.divideInPlace = function (otherVector) {
  2883. return this.divideToRef(otherVector, this);
  2884. };
  2885. /**
  2886. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2887. * @param other defines the second operand
  2888. * @returns the current updated Vector3
  2889. */
  2890. Vector3.prototype.minimizeInPlace = function (other) {
  2891. if (other.x < this.x)
  2892. this.x = other.x;
  2893. if (other.y < this.y)
  2894. this.y = other.y;
  2895. if (other.z < this.z)
  2896. this.z = other.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2901. * @param other defines the second operand
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.maximizeInPlace = function (other) {
  2905. if (other.x > this.x)
  2906. this.x = other.x;
  2907. if (other.y > this.y)
  2908. this.y = other.y;
  2909. if (other.z > this.z)
  2910. this.z = other.z;
  2911. return this;
  2912. };
  2913. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2914. /**
  2915. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2916. */
  2917. get: function () {
  2918. var absX = Math.abs(this.x);
  2919. var absY = Math.abs(this.y);
  2920. if (absX !== absY) {
  2921. return true;
  2922. }
  2923. var absZ = Math.abs(this.z);
  2924. if (absX !== absZ) {
  2925. return true;
  2926. }
  2927. if (absY !== absZ) {
  2928. return true;
  2929. }
  2930. return false;
  2931. },
  2932. enumerable: true,
  2933. configurable: true
  2934. });
  2935. // Properties
  2936. /**
  2937. * Gets the length of the Vector3
  2938. * @returns the length of the Vecto3
  2939. */
  2940. Vector3.prototype.length = function () {
  2941. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2942. };
  2943. /**
  2944. * Gets the squared length of the Vector3
  2945. * @returns squared length of the Vector3
  2946. */
  2947. Vector3.prototype.lengthSquared = function () {
  2948. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2949. };
  2950. /**
  2951. * Normalize the current Vector3.
  2952. * Please note that this is an in place operation.
  2953. * @returns the current updated Vector3
  2954. */
  2955. Vector3.prototype.normalize = function () {
  2956. var len = this.length();
  2957. if (len === 0 || len === 1.0)
  2958. return this;
  2959. var num = 1.0 / len;
  2960. this.x *= num;
  2961. this.y *= num;
  2962. this.z *= num;
  2963. return this;
  2964. };
  2965. /**
  2966. * Normalize the current Vector3 to a new vector
  2967. * @returns the new Vector3
  2968. */
  2969. Vector3.prototype.normalizeToNew = function () {
  2970. var normalized = new Vector3(0, 0, 0);
  2971. this.normalizeToRef(normalized);
  2972. return normalized;
  2973. };
  2974. /**
  2975. * Normalize the current Vector3 to the reference
  2976. * @param reference define the Vector3 to update
  2977. * @returns the updated Vector3
  2978. */
  2979. Vector3.prototype.normalizeToRef = function (reference) {
  2980. var len = this.length();
  2981. if (len === 0 || len === 1.0) {
  2982. reference.set(this.x, this.y, this.z);
  2983. return reference;
  2984. }
  2985. var scale = 1.0 / len;
  2986. this.scaleToRef(scale, reference);
  2987. return reference;
  2988. };
  2989. /**
  2990. * Creates a new Vector3 copied from the current Vector3
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.clone = function () {
  2994. return new Vector3(this.x, this.y, this.z);
  2995. };
  2996. /**
  2997. * Copies the passed vector coordinates to the current Vector3 ones
  2998. * @param source defines the source Vector3
  2999. * @returns the current updated Vector3
  3000. */
  3001. Vector3.prototype.copyFrom = function (source) {
  3002. this.x = source.x;
  3003. this.y = source.y;
  3004. this.z = source.z;
  3005. return this;
  3006. };
  3007. /**
  3008. * Copies the passed floats to the current Vector3 coordinates
  3009. * @param x defines the x coordinate of the operand
  3010. * @param y defines the y coordinate of the operand
  3011. * @param z defines the z coordinate of the operand
  3012. * @returns the current updated Vector3
  3013. */
  3014. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3015. this.x = x;
  3016. this.y = y;
  3017. this.z = z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Copies the passed floats to the current Vector3 coordinates
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.set = function (x, y, z) {
  3028. return this.copyFromFloats(x, y, z);
  3029. };
  3030. // Statics
  3031. /**
  3032. * Get the clip factor between two vectors
  3033. * @param vector0 defines the first operand
  3034. * @param vector1 defines the second operand
  3035. * @param axis defines the axis to use
  3036. * @param size defines the size along the axis
  3037. * @returns the clip factor
  3038. */
  3039. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3040. var d0 = Vector3.Dot(vector0, axis) - size;
  3041. var d1 = Vector3.Dot(vector1, axis) - size;
  3042. var s = d0 / (d0 - d1);
  3043. return s;
  3044. };
  3045. /**
  3046. * Get angle between two vectors
  3047. * @param vector0 angle between vector0 and vector1
  3048. * @param vector1 angle between vector0 and vector1
  3049. * @param normal direction of the normal
  3050. * @return the angle between vector0 and vector1
  3051. */
  3052. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3053. var v0 = vector0.clone().normalize();
  3054. var v1 = vector1.clone().normalize();
  3055. var dot = Vector3.Dot(v0, v1);
  3056. var n = Vector3.Cross(v0, v1);
  3057. if (Vector3.Dot(n, normal) > 0) {
  3058. return Math.acos(dot);
  3059. }
  3060. return -Math.acos(dot);
  3061. };
  3062. /**
  3063. * Returns a new Vector3 set from the index "offset" of the passed array
  3064. * @param array defines the source array
  3065. * @param offset defines the offset in the source array
  3066. * @returns the new Vector3
  3067. */
  3068. Vector3.FromArray = function (array, offset) {
  3069. if (!offset) {
  3070. offset = 0;
  3071. }
  3072. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3073. };
  3074. /**
  3075. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3076. * This function is deprecated. Use FromArray instead
  3077. * @param array defines the source array
  3078. * @param offset defines the offset in the source array
  3079. * @returns the new Vector3
  3080. */
  3081. Vector3.FromFloatArray = function (array, offset) {
  3082. return Vector3.FromArray(array, offset);
  3083. };
  3084. /**
  3085. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3086. * @param array defines the source array
  3087. * @param offset defines the offset in the source array
  3088. * @param result defines the Vector3 where to store the result
  3089. */
  3090. Vector3.FromArrayToRef = function (array, offset, result) {
  3091. result.x = array[offset];
  3092. result.y = array[offset + 1];
  3093. result.z = array[offset + 2];
  3094. };
  3095. /**
  3096. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3097. * This function is deprecated. Use FromArrayToRef instead.
  3098. * @param array defines the source array
  3099. * @param offset defines the offset in the source array
  3100. * @param result defines the Vector3 where to store the result
  3101. */
  3102. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3103. return Vector3.FromArrayToRef(array, offset, result);
  3104. };
  3105. /**
  3106. * Sets the passed vector "result" with the passed floats.
  3107. * @param x defines the x coordinate of the source
  3108. * @param y defines the y coordinate of the source
  3109. * @param z defines the z coordinate of the source
  3110. * @param result defines the Vector3 where to store the result
  3111. */
  3112. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3113. result.x = x;
  3114. result.y = y;
  3115. result.z = z;
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3119. * @returns a new empty Vector3
  3120. */
  3121. Vector3.Zero = function () {
  3122. return new Vector3(0.0, 0.0, 0.0);
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3126. * @returns a new unit Vector3
  3127. */
  3128. Vector3.One = function () {
  3129. return new Vector3(1.0, 1.0, 1.0);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3133. * @returns a new up Vector3
  3134. */
  3135. Vector3.Up = function () {
  3136. return new Vector3(0.0, 1.0, 0.0);
  3137. };
  3138. /**
  3139. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3140. * @returns a new forward Vector3
  3141. */
  3142. Vector3.Forward = function () {
  3143. return new Vector3(0.0, 0.0, 1.0);
  3144. };
  3145. /**
  3146. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3147. * @returns a new right Vector3
  3148. */
  3149. Vector3.Right = function () {
  3150. return new Vector3(1.0, 0.0, 0.0);
  3151. };
  3152. /**
  3153. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3154. * @returns a new left Vector3
  3155. */
  3156. Vector3.Left = function () {
  3157. return new Vector3(-1.0, 0.0, 0.0);
  3158. };
  3159. /**
  3160. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3161. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3162. * @param vector defines the Vector3 to transform
  3163. * @param transformation defines the transformation matrix
  3164. * @returns the transformed Vector3
  3165. */
  3166. Vector3.TransformCoordinates = function (vector, transformation) {
  3167. var result = Vector3.Zero();
  3168. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3169. return result;
  3170. };
  3171. /**
  3172. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3173. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3174. * @param vector defines the Vector3 to transform
  3175. * @param transformation defines the transformation matrix
  3176. * @param result defines the Vector3 where to store the result
  3177. */
  3178. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3179. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3180. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3181. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3182. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3183. result.x = x / w;
  3184. result.y = y / w;
  3185. result.z = z / w;
  3186. };
  3187. /**
  3188. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3189. * This method computes tranformed coordinates only, not transformed direction vectors
  3190. * @param x define the x coordinate of the source vector
  3191. * @param y define the y coordinate of the source vector
  3192. * @param z define the z coordinate of the source vector
  3193. * @param transformation defines the transformation matrix
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3197. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3198. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3199. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3200. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3201. result.x = rx / rw;
  3202. result.y = ry / rw;
  3203. result.z = rz / rw;
  3204. };
  3205. /**
  3206. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3207. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3208. * @param vector defines the Vector3 to transform
  3209. * @param transformation defines the transformation matrix
  3210. * @returns the new Vector3
  3211. */
  3212. Vector3.TransformNormal = function (vector, transformation) {
  3213. var result = Vector3.Zero();
  3214. Vector3.TransformNormalToRef(vector, transformation, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3219. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3220. * @param vector defines the Vector3 to transform
  3221. * @param transformation defines the transformation matrix
  3222. * @param result defines the Vector3 where to store the result
  3223. */
  3224. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3225. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3226. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3227. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3228. result.x = x;
  3229. result.y = y;
  3230. result.z = z;
  3231. };
  3232. /**
  3233. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3234. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3235. * @param x define the x coordinate of the source vector
  3236. * @param y define the y coordinate of the source vector
  3237. * @param z define the z coordinate of the source vector
  3238. * @param transformation defines the transformation matrix
  3239. * @param result defines the Vector3 where to store the result
  3240. */
  3241. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3242. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3243. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3244. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3248. * @param value1 defines the first control point
  3249. * @param value2 defines the second control point
  3250. * @param value3 defines the third control point
  3251. * @param value4 defines the fourth control point
  3252. * @param amount defines the amount on the spline to use
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3256. var squared = amount * amount;
  3257. var cubed = amount * squared;
  3258. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3259. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3260. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3261. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3262. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3263. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3264. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3265. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3266. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3267. return new Vector3(x, y, z);
  3268. };
  3269. /**
  3270. * 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"
  3271. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3272. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3273. * @param value defines the current value
  3274. * @param min defines the lower range value
  3275. * @param max defines the upper range value
  3276. * @returns the new Vector3
  3277. */
  3278. Vector3.Clamp = function (value, min, max) {
  3279. var x = value.x;
  3280. x = (x > max.x) ? max.x : x;
  3281. x = (x < min.x) ? min.x : x;
  3282. var y = value.y;
  3283. y = (y > max.y) ? max.y : y;
  3284. y = (y < min.y) ? min.y : y;
  3285. var z = value.z;
  3286. z = (z > max.z) ? max.z : z;
  3287. z = (z < min.z) ? min.z : z;
  3288. return new Vector3(x, y, z);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3292. * @param value1 defines the first control point
  3293. * @param tangent1 defines the first tangent vector
  3294. * @param value2 defines the second control point
  3295. * @param tangent2 defines the second tangent vector
  3296. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3297. * @returns the new Vector3
  3298. */
  3299. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3300. var squared = amount * amount;
  3301. var cubed = amount * squared;
  3302. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3303. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3304. var part3 = (cubed - (2.0 * squared)) + amount;
  3305. var part4 = cubed - squared;
  3306. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3307. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3308. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3309. return new Vector3(x, y, z);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3313. * @param start defines the start value
  3314. * @param end defines the end value
  3315. * @param amount max defines amount between both (between 0 and 1)
  3316. * @returns the new Vector3
  3317. */
  3318. Vector3.Lerp = function (start, end, amount) {
  3319. var result = new Vector3(0, 0, 0);
  3320. Vector3.LerpToRef(start, end, amount, result);
  3321. return result;
  3322. };
  3323. /**
  3324. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3325. * @param start defines the start value
  3326. * @param end defines the end value
  3327. * @param amount max defines amount between both (between 0 and 1)
  3328. * @param result defines the Vector3 where to store the result
  3329. */
  3330. Vector3.LerpToRef = function (start, end, amount, result) {
  3331. result.x = start.x + ((end.x - start.x) * amount);
  3332. result.y = start.y + ((end.y - start.y) * amount);
  3333. result.z = start.z + ((end.z - start.z) * amount);
  3334. };
  3335. /**
  3336. * Returns the dot product (float) between the vectors "left" and "right"
  3337. * @param left defines the left operand
  3338. * @param right defines the right operand
  3339. * @returns the dot product
  3340. */
  3341. Vector3.Dot = function (left, right) {
  3342. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3346. * The cross product is then orthogonal to both "left" and "right"
  3347. * @param left defines the left operand
  3348. * @param right defines the right operand
  3349. * @returns the cross product
  3350. */
  3351. Vector3.Cross = function (left, right) {
  3352. var result = Vector3.Zero();
  3353. Vector3.CrossToRef(left, right, result);
  3354. return result;
  3355. };
  3356. /**
  3357. * Sets the passed vector "result" with the cross product of "left" and "right"
  3358. * The cross product is then orthogonal to both "left" and "right"
  3359. * @param left defines the left operand
  3360. * @param right defines the right operand
  3361. * @param result defines the Vector3 where to store the result
  3362. */
  3363. Vector3.CrossToRef = function (left, right, result) {
  3364. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3365. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3366. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3367. result.copyFrom(MathTmp.Vector3[0]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 as the normalization of the passed vector
  3371. * @param vector defines the Vector3 to normalize
  3372. * @returns the new Vector3
  3373. */
  3374. Vector3.Normalize = function (vector) {
  3375. var result = Vector3.Zero();
  3376. Vector3.NormalizeToRef(vector, result);
  3377. return result;
  3378. };
  3379. /**
  3380. * Sets the passed vector "result" with the normalization of the passed first vector
  3381. * @param vector defines the Vector3 to normalize
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.NormalizeToRef = function (vector, result) {
  3385. result.copyFrom(vector);
  3386. result.normalize();
  3387. };
  3388. /**
  3389. * Project a Vector3 onto screen space
  3390. * @param vector defines the Vector3 to project
  3391. * @param world defines the world matrix to use
  3392. * @param transform defines the transform (view x projection) matrix to use
  3393. * @param viewport defines the screen viewport to use
  3394. * @returns the new Vector3
  3395. */
  3396. Vector3.Project = function (vector, world, transform, viewport) {
  3397. var cw = viewport.width;
  3398. var ch = viewport.height;
  3399. var cx = viewport.x;
  3400. var cy = viewport.y;
  3401. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3402. 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);
  3403. var matrix = MathTmp.Matrix[0];
  3404. world.multiplyToRef(transform, matrix);
  3405. matrix.multiplyToRef(viewportMatrix, matrix);
  3406. return Vector3.TransformCoordinates(vector, matrix);
  3407. };
  3408. /**
  3409. * Unproject from screen space to object space
  3410. * @param source defines the screen space Vector3 to use
  3411. * @param viewportWidth defines the current width of the viewport
  3412. * @param viewportHeight defines the current height of the viewport
  3413. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3414. * @param transform defines the transform (view x projection) matrix to use
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3418. var matrix = MathTmp.Matrix[0];
  3419. world.multiplyToRef(transform, matrix);
  3420. matrix.invert();
  3421. source.x = source.x / viewportWidth * 2 - 1;
  3422. source.y = -(source.y / viewportHeight * 2 - 1);
  3423. var vector = Vector3.TransformCoordinates(source, matrix);
  3424. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3425. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3426. vector = vector.scale(1.0 / num);
  3427. }
  3428. return vector;
  3429. };
  3430. /**
  3431. * Unproject from screen space to object space
  3432. * @param source defines the screen space Vector3 to use
  3433. * @param viewportWidth defines the current width of the viewport
  3434. * @param viewportHeight defines the current height of the viewport
  3435. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3436. * @param view defines the view matrix to use
  3437. * @param projection defines the projection matrix to use
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3441. var result = Vector3.Zero();
  3442. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Unproject from screen space to object space
  3447. * @param source defines the screen space Vector3 to use
  3448. * @param viewportWidth defines the current width of the viewport
  3449. * @param viewportHeight defines the current height of the viewport
  3450. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3451. * @param view defines the view matrix to use
  3452. * @param projection defines the projection matrix to use
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3456. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3457. };
  3458. /**
  3459. * Unproject from screen space to object space
  3460. * @param sourceX defines the screen space x coordinate to use
  3461. * @param sourceY defines the screen space y coordinate to use
  3462. * @param sourceZ defines the screen space z coordinate to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param view defines the view matrix to use
  3467. * @param projection defines the projection matrix to use
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3471. var matrix = MathTmp.Matrix[0];
  3472. world.multiplyToRef(view, matrix);
  3473. matrix.multiplyToRef(projection, matrix);
  3474. matrix.invert();
  3475. var screenSource = MathTmp.Vector3[0];
  3476. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3477. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3478. screenSource.z = 2 * sourceZ - 1.0;
  3479. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3480. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3481. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3482. result.scaleInPlace(1.0 / num);
  3483. }
  3484. };
  3485. /**
  3486. * Gets the minimal coordinate values between two Vector3
  3487. * @param left defines the first operand
  3488. * @param right defines the second operand
  3489. * @returns the new Vector3
  3490. */
  3491. Vector3.Minimize = function (left, right) {
  3492. var min = left.clone();
  3493. min.minimizeInPlace(right);
  3494. return min;
  3495. };
  3496. /**
  3497. * Gets the maximal coordinate values between two Vector3
  3498. * @param left defines the first operand
  3499. * @param right defines the second operand
  3500. * @returns the new Vector3
  3501. */
  3502. Vector3.Maximize = function (left, right) {
  3503. var max = left.clone();
  3504. max.maximizeInPlace(right);
  3505. return max;
  3506. };
  3507. /**
  3508. * Returns the distance between the vectors "value1" and "value2"
  3509. * @param value1 defines the first operand
  3510. * @param value2 defines the second operand
  3511. * @returns the distance
  3512. */
  3513. Vector3.Distance = function (value1, value2) {
  3514. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3515. };
  3516. /**
  3517. * Returns the squared distance between the vectors "value1" and "value2"
  3518. * @param value1 defines the first operand
  3519. * @param value2 defines the second operand
  3520. * @returns the squared distance
  3521. */
  3522. Vector3.DistanceSquared = function (value1, value2) {
  3523. var x = value1.x - value2.x;
  3524. var y = value1.y - value2.y;
  3525. var z = value1.z - value2.z;
  3526. return (x * x) + (y * y) + (z * z);
  3527. };
  3528. /**
  3529. * Returns a new Vector3 located at the center between "value1" and "value2"
  3530. * @param value1 defines the first operand
  3531. * @param value2 defines the second operand
  3532. * @returns the new Vector3
  3533. */
  3534. Vector3.Center = function (value1, value2) {
  3535. var center = value1.add(value2);
  3536. center.scaleInPlace(0.5);
  3537. return center;
  3538. };
  3539. /**
  3540. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3541. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3542. * to something in order to rotate it from its local system to the given target system
  3543. * Note: axis1, axis2 and axis3 are normalized during this operation
  3544. * @param axis1 defines the first axis
  3545. * @param axis2 defines the second axis
  3546. * @param axis3 defines the third axis
  3547. * @returns a new Vector3
  3548. */
  3549. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3550. var rotation = Vector3.Zero();
  3551. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3552. return rotation;
  3553. };
  3554. /**
  3555. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3556. * @param axis1 defines the first axis
  3557. * @param axis2 defines the second axis
  3558. * @param axis3 defines the third axis
  3559. * @param ref defines the Vector3 where to store the result
  3560. */
  3561. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3562. var quat = MathTmp.Quaternion[0];
  3563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3564. quat.toEulerAnglesToRef(ref);
  3565. };
  3566. return Vector3;
  3567. }());
  3568. BABYLON.Vector3 = Vector3;
  3569. //Vector4 class created for EulerAngle class conversion to Quaternion
  3570. var Vector4 = /** @class */ (function () {
  3571. /**
  3572. * Creates a Vector4 object from the passed floats.
  3573. */
  3574. function Vector4(x, y, z, w) {
  3575. this.x = x;
  3576. this.y = y;
  3577. this.z = z;
  3578. this.w = w;
  3579. }
  3580. /**
  3581. * Returns the string with the Vector4 coordinates.
  3582. */
  3583. Vector4.prototype.toString = function () {
  3584. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3585. };
  3586. /**
  3587. * Returns the string "Vector4".
  3588. */
  3589. Vector4.prototype.getClassName = function () {
  3590. return "Vector4";
  3591. };
  3592. /**
  3593. * Returns the Vector4 hash code.
  3594. */
  3595. Vector4.prototype.getHashCode = function () {
  3596. var hash = this.x || 0;
  3597. hash = (hash * 397) ^ (this.y || 0);
  3598. hash = (hash * 397) ^ (this.z || 0);
  3599. hash = (hash * 397) ^ (this.w || 0);
  3600. return hash;
  3601. };
  3602. // Operators
  3603. /**
  3604. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3605. */
  3606. Vector4.prototype.asArray = function () {
  3607. var result = new Array();
  3608. this.toArray(result, 0);
  3609. return result;
  3610. };
  3611. /**
  3612. * Populates the passed array from the passed index with the Vector4 coordinates.
  3613. * Returns the Vector4.
  3614. */
  3615. Vector4.prototype.toArray = function (array, index) {
  3616. if (index === undefined) {
  3617. index = 0;
  3618. }
  3619. array[index] = this.x;
  3620. array[index + 1] = this.y;
  3621. array[index + 2] = this.z;
  3622. array[index + 3] = this.w;
  3623. return this;
  3624. };
  3625. /**
  3626. * Adds the passed vector to the current Vector4.
  3627. * Returns the updated Vector4.
  3628. */
  3629. Vector4.prototype.addInPlace = function (otherVector) {
  3630. this.x += otherVector.x;
  3631. this.y += otherVector.y;
  3632. this.z += otherVector.z;
  3633. this.w += otherVector.w;
  3634. return this;
  3635. };
  3636. /**
  3637. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3638. */
  3639. Vector4.prototype.add = function (otherVector) {
  3640. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3641. };
  3642. /**
  3643. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3644. * Returns the current Vector4.
  3645. */
  3646. Vector4.prototype.addToRef = function (otherVector, result) {
  3647. result.x = this.x + otherVector.x;
  3648. result.y = this.y + otherVector.y;
  3649. result.z = this.z + otherVector.z;
  3650. result.w = this.w + otherVector.w;
  3651. return this;
  3652. };
  3653. /**
  3654. * Subtract in place the passed vector from the current Vector4.
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.subtractInPlace = function (otherVector) {
  3658. this.x -= otherVector.x;
  3659. this.y -= otherVector.y;
  3660. this.z -= otherVector.z;
  3661. this.w -= otherVector.w;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3666. */
  3667. Vector4.prototype.subtract = function (otherVector) {
  3668. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3675. result.x = this.x - otherVector.x;
  3676. result.y = this.y - otherVector.y;
  3677. result.z = this.z - otherVector.z;
  3678. result.w = this.w - otherVector.w;
  3679. return this;
  3680. };
  3681. /**
  3682. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3683. */
  3684. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3685. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3686. };
  3687. /**
  3688. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3689. * Returns the current Vector4.
  3690. */
  3691. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3692. result.x = this.x - x;
  3693. result.y = this.y - y;
  3694. result.z = this.z - z;
  3695. result.w = this.w - w;
  3696. return this;
  3697. };
  3698. /**
  3699. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3700. */
  3701. Vector4.prototype.negate = function () {
  3702. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3703. };
  3704. /**
  3705. * Multiplies the current Vector4 coordinates by scale (float).
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.scaleInPlace = function (scale) {
  3709. this.x *= scale;
  3710. this.y *= scale;
  3711. this.z *= scale;
  3712. this.w *= scale;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3717. */
  3718. Vector4.prototype.scale = function (scale) {
  3719. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3720. };
  3721. /**
  3722. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.scaleToRef = function (scale, result) {
  3726. result.x = this.x * scale;
  3727. result.y = this.y * scale;
  3728. result.z = this.z * scale;
  3729. result.w = this.w * scale;
  3730. return this;
  3731. };
  3732. /**
  3733. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3734. */
  3735. Vector4.prototype.equals = function (otherVector) {
  3736. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3737. };
  3738. /**
  3739. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3740. */
  3741. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3742. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3743. return otherVector
  3744. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3745. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3746. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3747. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3748. };
  3749. /**
  3750. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3751. */
  3752. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3753. return this.x === x && this.y === y && this.z === z && this.w === w;
  3754. };
  3755. /**
  3756. * Multiplies in place the current Vector4 by the passed one.
  3757. * Returns the updated Vector4.
  3758. */
  3759. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3760. this.x *= otherVector.x;
  3761. this.y *= otherVector.y;
  3762. this.z *= otherVector.z;
  3763. this.w *= otherVector.w;
  3764. return this;
  3765. };
  3766. /**
  3767. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3768. */
  3769. Vector4.prototype.multiply = function (otherVector) {
  3770. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3771. };
  3772. /**
  3773. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3774. * Returns the current Vector4.
  3775. */
  3776. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3777. result.x = this.x * otherVector.x;
  3778. result.y = this.y * otherVector.y;
  3779. result.z = this.z * otherVector.z;
  3780. result.w = this.w * otherVector.w;
  3781. return this;
  3782. };
  3783. /**
  3784. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3787. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3788. };
  3789. /**
  3790. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3791. */
  3792. Vector4.prototype.divide = function (otherVector) {
  3793. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3794. };
  3795. /**
  3796. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3797. * Returns the current Vector4.
  3798. */
  3799. Vector4.prototype.divideToRef = function (otherVector, result) {
  3800. result.x = this.x / otherVector.x;
  3801. result.y = this.y / otherVector.y;
  3802. result.z = this.z / otherVector.z;
  3803. result.w = this.w / otherVector.w;
  3804. return this;
  3805. };
  3806. /**
  3807. * Divides the current Vector3 coordinates by the passed ones.
  3808. * @returns the updated Vector3.
  3809. */
  3810. Vector4.prototype.divideInPlace = function (otherVector) {
  3811. return this.divideToRef(otherVector, this);
  3812. };
  3813. /**
  3814. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3815. * @param other defines the second operand
  3816. * @returns the current updated Vector4
  3817. */
  3818. Vector4.prototype.minimizeInPlace = function (other) {
  3819. if (other.x < this.x)
  3820. this.x = other.x;
  3821. if (other.y < this.y)
  3822. this.y = other.y;
  3823. if (other.z < this.z)
  3824. this.z = other.z;
  3825. if (other.w < this.w)
  3826. this.w = other.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3831. * @param other defines the second operand
  3832. * @returns the current updated Vector4
  3833. */
  3834. Vector4.prototype.maximizeInPlace = function (other) {
  3835. if (other.x > this.x)
  3836. this.x = other.x;
  3837. if (other.y > this.y)
  3838. this.y = other.y;
  3839. if (other.z > this.z)
  3840. this.z = other.z;
  3841. if (other.w > this.w)
  3842. this.w = other.w;
  3843. return this;
  3844. };
  3845. // Properties
  3846. /**
  3847. * Returns the Vector4 length (float).
  3848. */
  3849. Vector4.prototype.length = function () {
  3850. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3851. };
  3852. /**
  3853. * Returns the Vector4 squared length (float).
  3854. */
  3855. Vector4.prototype.lengthSquared = function () {
  3856. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3857. };
  3858. // Methods
  3859. /**
  3860. * Normalizes in place the Vector4.
  3861. * Returns the updated Vector4.
  3862. */
  3863. Vector4.prototype.normalize = function () {
  3864. var len = this.length();
  3865. if (len === 0)
  3866. return this;
  3867. var num = 1.0 / len;
  3868. this.x *= num;
  3869. this.y *= num;
  3870. this.z *= num;
  3871. this.w *= num;
  3872. return this;
  3873. };
  3874. /**
  3875. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3876. */
  3877. Vector4.prototype.toVector3 = function () {
  3878. return new Vector3(this.x, this.y, this.z);
  3879. };
  3880. /**
  3881. * Returns a new Vector4 copied from the current one.
  3882. */
  3883. Vector4.prototype.clone = function () {
  3884. return new Vector4(this.x, this.y, this.z, this.w);
  3885. };
  3886. /**
  3887. * Updates the current Vector4 with the passed one coordinates.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.copyFrom = function (source) {
  3891. this.x = source.x;
  3892. this.y = source.y;
  3893. this.z = source.z;
  3894. this.w = source.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Updates the current Vector4 coordinates with the passed floats.
  3899. * Returns the updated Vector4.
  3900. */
  3901. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3902. this.x = x;
  3903. this.y = y;
  3904. this.z = z;
  3905. this.w = w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Updates the current Vector4 coordinates with the passed floats.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.set = function (x, y, z, w) {
  3913. return this.copyFromFloats(x, y, z, w);
  3914. };
  3915. // Statics
  3916. /**
  3917. * Returns a new Vector4 set from the starting index of the passed array.
  3918. */
  3919. Vector4.FromArray = function (array, offset) {
  3920. if (!offset) {
  3921. offset = 0;
  3922. }
  3923. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3924. };
  3925. /**
  3926. * Updates the passed vector "result" from the starting index of the passed array.
  3927. */
  3928. Vector4.FromArrayToRef = function (array, offset, result) {
  3929. result.x = array[offset];
  3930. result.y = array[offset + 1];
  3931. result.z = array[offset + 2];
  3932. result.w = array[offset + 3];
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3936. */
  3937. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3938. Vector4.FromArrayToRef(array, offset, result);
  3939. };
  3940. /**
  3941. * Updates the passed vector "result" coordinates from the passed floats.
  3942. */
  3943. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3944. result.x = x;
  3945. result.y = y;
  3946. result.z = z;
  3947. result.w = w;
  3948. };
  3949. /**
  3950. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3951. */
  3952. Vector4.Zero = function () {
  3953. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3957. */
  3958. Vector4.One = function () {
  3959. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3960. };
  3961. /**
  3962. * Returns a new normalized Vector4 from the passed one.
  3963. */
  3964. Vector4.Normalize = function (vector) {
  3965. var result = Vector4.Zero();
  3966. Vector4.NormalizeToRef(vector, result);
  3967. return result;
  3968. };
  3969. /**
  3970. * Updates the passed vector "result" from the normalization of the passed one.
  3971. */
  3972. Vector4.NormalizeToRef = function (vector, result) {
  3973. result.copyFrom(vector);
  3974. result.normalize();
  3975. };
  3976. Vector4.Minimize = function (left, right) {
  3977. var min = left.clone();
  3978. min.minimizeInPlace(right);
  3979. return min;
  3980. };
  3981. Vector4.Maximize = function (left, right) {
  3982. var max = left.clone();
  3983. max.maximizeInPlace(right);
  3984. return max;
  3985. };
  3986. /**
  3987. * Returns the distance (float) between the vectors "value1" and "value2".
  3988. */
  3989. Vector4.Distance = function (value1, value2) {
  3990. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3991. };
  3992. /**
  3993. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3994. */
  3995. Vector4.DistanceSquared = function (value1, value2) {
  3996. var x = value1.x - value2.x;
  3997. var y = value1.y - value2.y;
  3998. var z = value1.z - value2.z;
  3999. var w = value1.w - value2.w;
  4000. return (x * x) + (y * y) + (z * z) + (w * w);
  4001. };
  4002. /**
  4003. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4004. */
  4005. Vector4.Center = function (value1, value2) {
  4006. var center = value1.add(value2);
  4007. center.scaleInPlace(0.5);
  4008. return center;
  4009. };
  4010. /**
  4011. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4012. * This methods computes transformed normalized direction vectors only.
  4013. */
  4014. Vector4.TransformNormal = function (vector, transformation) {
  4015. var result = Vector4.Zero();
  4016. Vector4.TransformNormalToRef(vector, transformation, result);
  4017. return result;
  4018. };
  4019. /**
  4020. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4021. * This methods computes transformed normalized direction vectors only.
  4022. */
  4023. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4024. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4025. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4026. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4027. result.x = x;
  4028. result.y = y;
  4029. result.z = z;
  4030. result.w = vector.w;
  4031. };
  4032. /**
  4033. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4034. * This methods computes transformed normalized direction vectors only.
  4035. */
  4036. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4037. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4038. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4039. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4040. result.w = w;
  4041. };
  4042. return Vector4;
  4043. }());
  4044. BABYLON.Vector4 = Vector4;
  4045. var Size = /** @class */ (function () {
  4046. /**
  4047. * Creates a Size object from the passed width and height (floats).
  4048. */
  4049. function Size(width, height) {
  4050. this.width = width;
  4051. this.height = height;
  4052. }
  4053. // Returns a string with the Size width and height.
  4054. Size.prototype.toString = function () {
  4055. return "{W: " + this.width + ", H: " + this.height + "}";
  4056. };
  4057. /**
  4058. * Returns the string "Size"
  4059. */
  4060. Size.prototype.getClassName = function () {
  4061. return "Size";
  4062. };
  4063. /**
  4064. * Returns the Size hash code.
  4065. */
  4066. Size.prototype.getHashCode = function () {
  4067. var hash = this.width || 0;
  4068. hash = (hash * 397) ^ (this.height || 0);
  4069. return hash;
  4070. };
  4071. /**
  4072. * Updates the current size from the passed one.
  4073. * Returns the updated Size.
  4074. */
  4075. Size.prototype.copyFrom = function (src) {
  4076. this.width = src.width;
  4077. this.height = src.height;
  4078. };
  4079. /**
  4080. * Updates in place the current Size from the passed floats.
  4081. * Returns the updated Size.
  4082. */
  4083. Size.prototype.copyFromFloats = function (width, height) {
  4084. this.width = width;
  4085. this.height = height;
  4086. return this;
  4087. };
  4088. /**
  4089. * Updates in place the current Size from the passed floats.
  4090. * Returns the updated Size.
  4091. */
  4092. Size.prototype.set = function (width, height) {
  4093. return this.copyFromFloats(width, height);
  4094. };
  4095. /**
  4096. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4097. */
  4098. Size.prototype.multiplyByFloats = function (w, h) {
  4099. return new Size(this.width * w, this.height * h);
  4100. };
  4101. /**
  4102. * Returns a new Size copied from the passed one.
  4103. */
  4104. Size.prototype.clone = function () {
  4105. return new Size(this.width, this.height);
  4106. };
  4107. /**
  4108. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4109. */
  4110. Size.prototype.equals = function (other) {
  4111. if (!other) {
  4112. return false;
  4113. }
  4114. return (this.width === other.width) && (this.height === other.height);
  4115. };
  4116. Object.defineProperty(Size.prototype, "surface", {
  4117. /**
  4118. * Returns the surface of the Size : width * height (float).
  4119. */
  4120. get: function () {
  4121. return this.width * this.height;
  4122. },
  4123. enumerable: true,
  4124. configurable: true
  4125. });
  4126. /**
  4127. * Returns a new Size set to (0.0, 0.0)
  4128. */
  4129. Size.Zero = function () {
  4130. return new Size(0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Size set as the addition result of the current Size and the passed one.
  4134. */
  4135. Size.prototype.add = function (otherSize) {
  4136. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4137. return r;
  4138. };
  4139. /**
  4140. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4141. */
  4142. Size.prototype.subtract = function (otherSize) {
  4143. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4144. return r;
  4145. };
  4146. /**
  4147. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4148. */
  4149. Size.Lerp = function (start, end, amount) {
  4150. var w = start.width + ((end.width - start.width) * amount);
  4151. var h = start.height + ((end.height - start.height) * amount);
  4152. return new Size(w, h);
  4153. };
  4154. return Size;
  4155. }());
  4156. BABYLON.Size = Size;
  4157. var Quaternion = /** @class */ (function () {
  4158. /**
  4159. * Creates a new Quaternion from the passed floats.
  4160. */
  4161. function Quaternion(x, y, z, w) {
  4162. if (x === void 0) { x = 0.0; }
  4163. if (y === void 0) { y = 0.0; }
  4164. if (z === void 0) { z = 0.0; }
  4165. if (w === void 0) { w = 1.0; }
  4166. this.x = x;
  4167. this.y = y;
  4168. this.z = z;
  4169. this.w = w;
  4170. }
  4171. /**
  4172. * Returns a string with the Quaternion coordinates.
  4173. */
  4174. Quaternion.prototype.toString = function () {
  4175. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4176. };
  4177. /**
  4178. * Returns the string "Quaternion".
  4179. */
  4180. Quaternion.prototype.getClassName = function () {
  4181. return "Quaternion";
  4182. };
  4183. /**
  4184. * Returns the Quaternion hash code.
  4185. */
  4186. Quaternion.prototype.getHashCode = function () {
  4187. var hash = this.x || 0;
  4188. hash = (hash * 397) ^ (this.y || 0);
  4189. hash = (hash * 397) ^ (this.z || 0);
  4190. hash = (hash * 397) ^ (this.w || 0);
  4191. return hash;
  4192. };
  4193. /**
  4194. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4195. */
  4196. Quaternion.prototype.asArray = function () {
  4197. return [this.x, this.y, this.z, this.w];
  4198. };
  4199. /**
  4200. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4201. */
  4202. Quaternion.prototype.equals = function (otherQuaternion) {
  4203. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4204. };
  4205. /**
  4206. * Returns a new Quaternion copied from the current one.
  4207. */
  4208. Quaternion.prototype.clone = function () {
  4209. return new Quaternion(this.x, this.y, this.z, this.w);
  4210. };
  4211. /**
  4212. * Updates the current Quaternion from the passed one coordinates.
  4213. * Returns the updated Quaterion.
  4214. */
  4215. Quaternion.prototype.copyFrom = function (other) {
  4216. this.x = other.x;
  4217. this.y = other.y;
  4218. this.z = other.z;
  4219. this.w = other.w;
  4220. return this;
  4221. };
  4222. /**
  4223. * Updates the current Quaternion from the passed float coordinates.
  4224. * Returns the updated Quaterion.
  4225. */
  4226. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4227. this.x = x;
  4228. this.y = y;
  4229. this.z = z;
  4230. this.w = w;
  4231. return this;
  4232. };
  4233. /**
  4234. * Updates the current Quaternion from the passed float coordinates.
  4235. * Returns the updated Quaterion.
  4236. */
  4237. Quaternion.prototype.set = function (x, y, z, w) {
  4238. return this.copyFromFloats(x, y, z, w);
  4239. };
  4240. /**
  4241. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4242. */
  4243. Quaternion.prototype.add = function (other) {
  4244. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4245. };
  4246. /**
  4247. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4248. */
  4249. Quaternion.prototype.subtract = function (other) {
  4250. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4251. };
  4252. /**
  4253. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4254. */
  4255. Quaternion.prototype.scale = function (value) {
  4256. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4257. };
  4258. /**
  4259. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4260. */
  4261. Quaternion.prototype.multiply = function (q1) {
  4262. var result = new Quaternion(0, 0, 0, 1.0);
  4263. this.multiplyToRef(q1, result);
  4264. return result;
  4265. };
  4266. /**
  4267. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4268. * Returns the current Quaternion.
  4269. */
  4270. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4271. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4272. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4273. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4274. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4275. result.copyFromFloats(x, y, z, w);
  4276. return this;
  4277. };
  4278. /**
  4279. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4280. * Returns the updated Quaternion.
  4281. */
  4282. Quaternion.prototype.multiplyInPlace = function (q1) {
  4283. this.multiplyToRef(q1, this);
  4284. return this;
  4285. };
  4286. /**
  4287. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4288. * Returns the current Quaternion.
  4289. */
  4290. Quaternion.prototype.conjugateToRef = function (ref) {
  4291. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4292. return this;
  4293. };
  4294. /**
  4295. * Conjugates in place the current Quaternion.
  4296. * Returns the updated Quaternion.
  4297. */
  4298. Quaternion.prototype.conjugateInPlace = function () {
  4299. this.x *= -1;
  4300. this.y *= -1;
  4301. this.z *= -1;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4306. */
  4307. Quaternion.prototype.conjugate = function () {
  4308. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4309. return result;
  4310. };
  4311. /**
  4312. * Returns the Quaternion length (float).
  4313. */
  4314. Quaternion.prototype.length = function () {
  4315. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4316. };
  4317. /**
  4318. * Normalize in place the current Quaternion.
  4319. * Returns the updated Quaternion.
  4320. */
  4321. Quaternion.prototype.normalize = function () {
  4322. var length = 1.0 / this.length();
  4323. this.x *= length;
  4324. this.y *= length;
  4325. this.z *= length;
  4326. this.w *= length;
  4327. return this;
  4328. };
  4329. /**
  4330. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4331. */
  4332. Quaternion.prototype.toEulerAngles = function (order) {
  4333. if (order === void 0) { order = "YZX"; }
  4334. var result = Vector3.Zero();
  4335. this.toEulerAnglesToRef(result, order);
  4336. return result;
  4337. };
  4338. /**
  4339. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4340. * Returns the current Quaternion.
  4341. */
  4342. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4343. if (order === void 0) { order = "YZX"; }
  4344. var qz = this.z;
  4345. var qx = this.x;
  4346. var qy = this.y;
  4347. var qw = this.w;
  4348. var sqw = qw * qw;
  4349. var sqz = qz * qz;
  4350. var sqx = qx * qx;
  4351. var sqy = qy * qy;
  4352. var zAxisY = qy * qz - qx * qw;
  4353. var limit = .4999999;
  4354. if (zAxisY < -limit) {
  4355. result.y = 2 * Math.atan2(qy, qw);
  4356. result.x = Math.PI / 2;
  4357. result.z = 0;
  4358. }
  4359. else if (zAxisY > limit) {
  4360. result.y = 2 * Math.atan2(qy, qw);
  4361. result.x = -Math.PI / 2;
  4362. result.z = 0;
  4363. }
  4364. else {
  4365. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4366. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4367. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4368. }
  4369. return this;
  4370. };
  4371. /**
  4372. * Updates the passed rotation matrix with the current Quaternion values.
  4373. * Returns the current Quaternion.
  4374. */
  4375. Quaternion.prototype.toRotationMatrix = function (result) {
  4376. var xx = this.x * this.x;
  4377. var yy = this.y * this.y;
  4378. var zz = this.z * this.z;
  4379. var xy = this.x * this.y;
  4380. var zw = this.z * this.w;
  4381. var zx = this.z * this.x;
  4382. var yw = this.y * this.w;
  4383. var yz = this.y * this.z;
  4384. var xw = this.x * this.w;
  4385. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4386. result.m[1] = 2.0 * (xy + zw);
  4387. result.m[2] = 2.0 * (zx - yw);
  4388. result.m[3] = 0;
  4389. result.m[4] = 2.0 * (xy - zw);
  4390. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4391. result.m[6] = 2.0 * (yz + xw);
  4392. result.m[7] = 0;
  4393. result.m[8] = 2.0 * (zx + yw);
  4394. result.m[9] = 2.0 * (yz - xw);
  4395. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4396. result.m[11] = 0;
  4397. result.m[12] = 0;
  4398. result.m[13] = 0;
  4399. result.m[14] = 0;
  4400. result.m[15] = 1.0;
  4401. result._markAsUpdated();
  4402. return this;
  4403. };
  4404. /**
  4405. * Updates the current Quaternion from the passed rotation matrix values.
  4406. * Returns the updated Quaternion.
  4407. */
  4408. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4409. Quaternion.FromRotationMatrixToRef(matrix, this);
  4410. return this;
  4411. };
  4412. // Statics
  4413. /**
  4414. * Returns a new Quaternion set from the passed rotation matrix values.
  4415. */
  4416. Quaternion.FromRotationMatrix = function (matrix) {
  4417. var result = new Quaternion();
  4418. Quaternion.FromRotationMatrixToRef(matrix, result);
  4419. return result;
  4420. };
  4421. /**
  4422. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4423. */
  4424. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4425. var data = matrix.m;
  4426. var m11 = data[0], m12 = data[4], m13 = data[8];
  4427. var m21 = data[1], m22 = data[5], m23 = data[9];
  4428. var m31 = data[2], m32 = data[6], m33 = data[10];
  4429. var trace = m11 + m22 + m33;
  4430. var s;
  4431. if (trace > 0) {
  4432. s = 0.5 / Math.sqrt(trace + 1.0);
  4433. result.w = 0.25 / s;
  4434. result.x = (m32 - m23) * s;
  4435. result.y = (m13 - m31) * s;
  4436. result.z = (m21 - m12) * s;
  4437. }
  4438. else if (m11 > m22 && m11 > m33) {
  4439. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4440. result.w = (m32 - m23) / s;
  4441. result.x = 0.25 * s;
  4442. result.y = (m12 + m21) / s;
  4443. result.z = (m13 + m31) / s;
  4444. }
  4445. else if (m22 > m33) {
  4446. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4447. result.w = (m13 - m31) / s;
  4448. result.x = (m12 + m21) / s;
  4449. result.y = 0.25 * s;
  4450. result.z = (m23 + m32) / s;
  4451. }
  4452. else {
  4453. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4454. result.w = (m21 - m12) / s;
  4455. result.x = (m13 + m31) / s;
  4456. result.y = (m23 + m32) / s;
  4457. result.z = 0.25 * s;
  4458. }
  4459. };
  4460. /**
  4461. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4462. */
  4463. Quaternion.Zero = function () {
  4464. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4465. };
  4466. /**
  4467. * Returns a new Quaternion as the inverted current Quaternion.
  4468. */
  4469. Quaternion.Inverse = function (q) {
  4470. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4471. };
  4472. /**
  4473. * Returns the identity Quaternion.
  4474. */
  4475. Quaternion.Identity = function () {
  4476. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4477. };
  4478. Quaternion.IsIdentity = function (quaternion) {
  4479. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4480. };
  4481. /**
  4482. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4483. */
  4484. Quaternion.RotationAxis = function (axis, angle) {
  4485. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4486. };
  4487. /**
  4488. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4489. */
  4490. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4491. var sin = Math.sin(angle / 2);
  4492. axis.normalize();
  4493. result.w = Math.cos(angle / 2);
  4494. result.x = axis.x * sin;
  4495. result.y = axis.y * sin;
  4496. result.z = axis.z * sin;
  4497. return result;
  4498. };
  4499. /**
  4500. * Retuns a new Quaternion set from the starting index of the passed array.
  4501. */
  4502. Quaternion.FromArray = function (array, offset) {
  4503. if (!offset) {
  4504. offset = 0;
  4505. }
  4506. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4507. };
  4508. /**
  4509. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4510. */
  4511. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4512. var q = new Quaternion();
  4513. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4514. return q;
  4515. };
  4516. /**
  4517. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4518. */
  4519. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4520. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4521. var halfRoll = roll * 0.5;
  4522. var halfPitch = pitch * 0.5;
  4523. var halfYaw = yaw * 0.5;
  4524. var sinRoll = Math.sin(halfRoll);
  4525. var cosRoll = Math.cos(halfRoll);
  4526. var sinPitch = Math.sin(halfPitch);
  4527. var cosPitch = Math.cos(halfPitch);
  4528. var sinYaw = Math.sin(halfYaw);
  4529. var cosYaw = Math.cos(halfYaw);
  4530. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4531. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4532. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4533. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4534. };
  4535. /**
  4536. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4537. */
  4538. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4539. var result = new Quaternion();
  4540. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4541. return result;
  4542. };
  4543. /**
  4544. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4545. */
  4546. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4547. // Produces a quaternion from Euler angles in the z-x-z orientation
  4548. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4549. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4550. var halfBeta = beta * 0.5;
  4551. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4552. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4553. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4554. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4555. };
  4556. /**
  4557. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4558. * cf to Vector3.RotationFromAxis() documentation.
  4559. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4560. */
  4561. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4562. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4563. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4564. return quat;
  4565. };
  4566. /**
  4567. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4568. * cf to Vector3.RotationFromAxis() documentation.
  4569. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4570. */
  4571. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4572. var rotMat = MathTmp.Matrix[0];
  4573. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4574. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4575. };
  4576. Quaternion.Slerp = function (left, right, amount) {
  4577. var result = Quaternion.Identity();
  4578. Quaternion.SlerpToRef(left, right, amount, result);
  4579. return result;
  4580. };
  4581. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4582. var num2;
  4583. var num3;
  4584. var num = amount;
  4585. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4586. var flag = false;
  4587. if (num4 < 0) {
  4588. flag = true;
  4589. num4 = -num4;
  4590. }
  4591. if (num4 > 0.999999) {
  4592. num3 = 1 - num;
  4593. num2 = flag ? -num : num;
  4594. }
  4595. else {
  4596. var num5 = Math.acos(num4);
  4597. var num6 = (1.0 / Math.sin(num5));
  4598. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4599. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4600. }
  4601. result.x = (num3 * left.x) + (num2 * right.x);
  4602. result.y = (num3 * left.y) + (num2 * right.y);
  4603. result.z = (num3 * left.z) + (num2 * right.z);
  4604. result.w = (num3 * left.w) + (num2 * right.w);
  4605. };
  4606. /**
  4607. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4608. */
  4609. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4610. var squared = amount * amount;
  4611. var cubed = amount * squared;
  4612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4614. var part3 = (cubed - (2.0 * squared)) + amount;
  4615. var part4 = cubed - squared;
  4616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4619. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4620. return new Quaternion(x, y, z, w);
  4621. };
  4622. return Quaternion;
  4623. }());
  4624. BABYLON.Quaternion = Quaternion;
  4625. var Matrix = /** @class */ (function () {
  4626. function Matrix() {
  4627. this._isIdentity = false;
  4628. this._isIdentityDirty = true;
  4629. this.m = new Float32Array(16);
  4630. this._markAsUpdated();
  4631. }
  4632. Matrix.prototype._markAsUpdated = function () {
  4633. this.updateFlag = Matrix._updateFlagSeed++;
  4634. this._isIdentityDirty = true;
  4635. };
  4636. // Properties
  4637. /**
  4638. * Boolean : True is the matrix is the identity matrix
  4639. */
  4640. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4641. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4642. if (this._isIdentityDirty) {
  4643. this._isIdentityDirty = false;
  4644. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4645. this._isIdentity = false;
  4646. }
  4647. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4648. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4649. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4650. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4651. this._isIdentity = false;
  4652. }
  4653. else {
  4654. this._isIdentity = true;
  4655. }
  4656. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4657. this._isIdentity = false;
  4658. }
  4659. }
  4660. return this._isIdentity;
  4661. };
  4662. /**
  4663. * Returns the matrix determinant (float).
  4664. */
  4665. Matrix.prototype.determinant = function () {
  4666. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4667. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4668. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4669. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4670. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4671. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4672. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4673. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4674. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4675. };
  4676. // Methods
  4677. /**
  4678. * Returns the matrix underlying array.
  4679. */
  4680. Matrix.prototype.toArray = function () {
  4681. return this.m;
  4682. };
  4683. /**
  4684. * Returns the matrix underlying array.
  4685. */
  4686. Matrix.prototype.asArray = function () {
  4687. return this.toArray();
  4688. };
  4689. /**
  4690. * Inverts in place the Matrix.
  4691. * Returns the Matrix inverted.
  4692. */
  4693. Matrix.prototype.invert = function () {
  4694. this.invertToRef(this);
  4695. return this;
  4696. };
  4697. /**
  4698. * Sets all the matrix elements to zero.
  4699. * Returns the Matrix.
  4700. */
  4701. Matrix.prototype.reset = function () {
  4702. for (var index = 0; index < 16; index++) {
  4703. this.m[index] = 0.0;
  4704. }
  4705. this._markAsUpdated();
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4710. */
  4711. Matrix.prototype.add = function (other) {
  4712. var result = new Matrix();
  4713. this.addToRef(other, result);
  4714. return result;
  4715. };
  4716. /**
  4717. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4718. * Returns the Matrix.
  4719. */
  4720. Matrix.prototype.addToRef = function (other, result) {
  4721. for (var index = 0; index < 16; index++) {
  4722. result.m[index] = this.m[index] + other.m[index];
  4723. }
  4724. result._markAsUpdated();
  4725. return this;
  4726. };
  4727. /**
  4728. * Adds in place the passed matrix to the current Matrix.
  4729. * Returns the updated Matrix.
  4730. */
  4731. Matrix.prototype.addToSelf = function (other) {
  4732. for (var index = 0; index < 16; index++) {
  4733. this.m[index] += other.m[index];
  4734. }
  4735. this._markAsUpdated();
  4736. return this;
  4737. };
  4738. /**
  4739. * Sets the passed matrix with the current inverted Matrix.
  4740. * Returns the unmodified current Matrix.
  4741. */
  4742. Matrix.prototype.invertToRef = function (other) {
  4743. var l1 = this.m[0];
  4744. var l2 = this.m[1];
  4745. var l3 = this.m[2];
  4746. var l4 = this.m[3];
  4747. var l5 = this.m[4];
  4748. var l6 = this.m[5];
  4749. var l7 = this.m[6];
  4750. var l8 = this.m[7];
  4751. var l9 = this.m[8];
  4752. var l10 = this.m[9];
  4753. var l11 = this.m[10];
  4754. var l12 = this.m[11];
  4755. var l13 = this.m[12];
  4756. var l14 = this.m[13];
  4757. var l15 = this.m[14];
  4758. var l16 = this.m[15];
  4759. var l17 = (l11 * l16) - (l12 * l15);
  4760. var l18 = (l10 * l16) - (l12 * l14);
  4761. var l19 = (l10 * l15) - (l11 * l14);
  4762. var l20 = (l9 * l16) - (l12 * l13);
  4763. var l21 = (l9 * l15) - (l11 * l13);
  4764. var l22 = (l9 * l14) - (l10 * l13);
  4765. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4766. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4767. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4768. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4769. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4770. var l28 = (l7 * l16) - (l8 * l15);
  4771. var l29 = (l6 * l16) - (l8 * l14);
  4772. var l30 = (l6 * l15) - (l7 * l14);
  4773. var l31 = (l5 * l16) - (l8 * l13);
  4774. var l32 = (l5 * l15) - (l7 * l13);
  4775. var l33 = (l5 * l14) - (l6 * l13);
  4776. var l34 = (l7 * l12) - (l8 * l11);
  4777. var l35 = (l6 * l12) - (l8 * l10);
  4778. var l36 = (l6 * l11) - (l7 * l10);
  4779. var l37 = (l5 * l12) - (l8 * l9);
  4780. var l38 = (l5 * l11) - (l7 * l9);
  4781. var l39 = (l5 * l10) - (l6 * l9);
  4782. other.m[0] = l23 * l27;
  4783. other.m[4] = l24 * l27;
  4784. other.m[8] = l25 * l27;
  4785. other.m[12] = l26 * l27;
  4786. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4787. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4788. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4789. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4790. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4791. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4792. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4793. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4794. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4795. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4796. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4797. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4798. other._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4803. * Returns the updated Matrix.
  4804. */
  4805. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4806. this.m[12] = x;
  4807. this.m[13] = y;
  4808. this.m[14] = z;
  4809. this._markAsUpdated();
  4810. return this;
  4811. };
  4812. /**
  4813. * Inserts the translation vector in the current Matrix.
  4814. * Returns the updated Matrix.
  4815. */
  4816. Matrix.prototype.setTranslation = function (vector3) {
  4817. this.m[12] = vector3.x;
  4818. this.m[13] = vector3.y;
  4819. this.m[14] = vector3.z;
  4820. this._markAsUpdated();
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Vector3 as the extracted translation from the Matrix.
  4825. */
  4826. Matrix.prototype.getTranslation = function () {
  4827. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4828. };
  4829. /**
  4830. * Fill a Vector3 with the extracted translation from the Matrix.
  4831. */
  4832. Matrix.prototype.getTranslationToRef = function (result) {
  4833. result.x = this.m[12];
  4834. result.y = this.m[13];
  4835. result.z = this.m[14];
  4836. return this;
  4837. };
  4838. /**
  4839. * Remove rotation and scaling part from the Matrix.
  4840. * Returns the updated Matrix.
  4841. */
  4842. Matrix.prototype.removeRotationAndScaling = function () {
  4843. this.setRowFromFloats(0, 1, 0, 0, 0);
  4844. this.setRowFromFloats(1, 0, 1, 0, 0);
  4845. this.setRowFromFloats(2, 0, 0, 1, 0);
  4846. return this;
  4847. };
  4848. /**
  4849. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4850. */
  4851. Matrix.prototype.multiply = function (other) {
  4852. var result = new Matrix();
  4853. this.multiplyToRef(other, result);
  4854. return result;
  4855. };
  4856. /**
  4857. * Updates the current Matrix from the passed one values.
  4858. * Returns the updated Matrix.
  4859. */
  4860. Matrix.prototype.copyFrom = function (other) {
  4861. for (var index = 0; index < 16; index++) {
  4862. this.m[index] = other.m[index];
  4863. }
  4864. this._markAsUpdated();
  4865. return this;
  4866. };
  4867. /**
  4868. * Populates the passed array from the starting index with the Matrix values.
  4869. * Returns the Matrix.
  4870. */
  4871. Matrix.prototype.copyToArray = function (array, offset) {
  4872. if (offset === void 0) { offset = 0; }
  4873. for (var index = 0; index < 16; index++) {
  4874. array[offset + index] = this.m[index];
  4875. }
  4876. return this;
  4877. };
  4878. /**
  4879. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4880. */
  4881. Matrix.prototype.multiplyToRef = function (other, result) {
  4882. this.multiplyToArray(other, result.m, 0);
  4883. result._markAsUpdated();
  4884. return this;
  4885. };
  4886. /**
  4887. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4888. */
  4889. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4890. var tm0 = this.m[0];
  4891. var tm1 = this.m[1];
  4892. var tm2 = this.m[2];
  4893. var tm3 = this.m[3];
  4894. var tm4 = this.m[4];
  4895. var tm5 = this.m[5];
  4896. var tm6 = this.m[6];
  4897. var tm7 = this.m[7];
  4898. var tm8 = this.m[8];
  4899. var tm9 = this.m[9];
  4900. var tm10 = this.m[10];
  4901. var tm11 = this.m[11];
  4902. var tm12 = this.m[12];
  4903. var tm13 = this.m[13];
  4904. var tm14 = this.m[14];
  4905. var tm15 = this.m[15];
  4906. var om0 = other.m[0];
  4907. var om1 = other.m[1];
  4908. var om2 = other.m[2];
  4909. var om3 = other.m[3];
  4910. var om4 = other.m[4];
  4911. var om5 = other.m[5];
  4912. var om6 = other.m[6];
  4913. var om7 = other.m[7];
  4914. var om8 = other.m[8];
  4915. var om9 = other.m[9];
  4916. var om10 = other.m[10];
  4917. var om11 = other.m[11];
  4918. var om12 = other.m[12];
  4919. var om13 = other.m[13];
  4920. var om14 = other.m[14];
  4921. var om15 = other.m[15];
  4922. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4923. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4924. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4925. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4926. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4927. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4928. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4929. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4930. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4931. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4932. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4933. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4934. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4935. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4936. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4937. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4938. return this;
  4939. };
  4940. /**
  4941. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4942. */
  4943. Matrix.prototype.equals = function (value) {
  4944. return value &&
  4945. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4946. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4947. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4948. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4949. };
  4950. /**
  4951. * Returns a new Matrix from the current Matrix.
  4952. */
  4953. Matrix.prototype.clone = function () {
  4954. 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]);
  4955. };
  4956. /**
  4957. * Returns the string "Matrix"
  4958. */
  4959. Matrix.prototype.getClassName = function () {
  4960. return "Matrix";
  4961. };
  4962. /**
  4963. * Returns the Matrix hash code.
  4964. */
  4965. Matrix.prototype.getHashCode = function () {
  4966. var hash = this.m[0] || 0;
  4967. for (var i = 1; i < 16; i++) {
  4968. hash = (hash * 397) ^ (this.m[i] || 0);
  4969. }
  4970. return hash;
  4971. };
  4972. /**
  4973. * Decomposes the current Matrix into :
  4974. * - a scale vector3 passed as a reference to update,
  4975. * - a rotation quaternion passed as a reference to update,
  4976. * - a translation vector3 passed as a reference to update.
  4977. * Returns the true if operation was successful.
  4978. */
  4979. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4980. translation.x = this.m[12];
  4981. translation.y = this.m[13];
  4982. translation.z = this.m[14];
  4983. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4984. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4985. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4986. if (this.determinant() <= 0) {
  4987. scale.y *= -1;
  4988. }
  4989. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4990. rotation.x = 0;
  4991. rotation.y = 0;
  4992. rotation.z = 0;
  4993. rotation.w = 1;
  4994. return false;
  4995. }
  4996. 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]);
  4997. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4998. return true;
  4999. };
  5000. /**
  5001. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5002. * @param ref matrix to store the result
  5003. */
  5004. Matrix.prototype.toNormalMatrix = function (ref) {
  5005. this.invertToRef(ref);
  5006. ref.transpose();
  5007. var m = ref.m;
  5008. 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);
  5009. };
  5010. /**
  5011. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5012. */
  5013. Matrix.prototype.getRotationMatrix = function () {
  5014. var result = Matrix.Identity();
  5015. this.getRotationMatrixToRef(result);
  5016. return result;
  5017. };
  5018. /**
  5019. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5020. * Returns the current Matrix.
  5021. */
  5022. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5023. var m = this.m;
  5024. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5025. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5026. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5027. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5028. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5029. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5030. 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);
  5031. return this;
  5032. };
  5033. // Statics
  5034. /**
  5035. * Returns a new Matrix set from the starting index of the passed array.
  5036. */
  5037. Matrix.FromArray = function (array, offset) {
  5038. var result = new Matrix();
  5039. if (!offset) {
  5040. offset = 0;
  5041. }
  5042. Matrix.FromArrayToRef(array, offset, result);
  5043. return result;
  5044. };
  5045. /**
  5046. * Sets the passed "result" matrix from the starting index of the passed array.
  5047. */
  5048. Matrix.FromArrayToRef = function (array, offset, result) {
  5049. for (var index = 0; index < 16; index++) {
  5050. result.m[index] = array[index + offset];
  5051. }
  5052. result._markAsUpdated();
  5053. };
  5054. /**
  5055. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5056. */
  5057. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5058. for (var index = 0; index < 16; index++) {
  5059. result.m[index] = array[index + offset] * scale;
  5060. }
  5061. result._markAsUpdated();
  5062. };
  5063. /**
  5064. * Sets the passed matrix "result" with the 16 passed floats.
  5065. */
  5066. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5067. result.m[0] = initialM11;
  5068. result.m[1] = initialM12;
  5069. result.m[2] = initialM13;
  5070. result.m[3] = initialM14;
  5071. result.m[4] = initialM21;
  5072. result.m[5] = initialM22;
  5073. result.m[6] = initialM23;
  5074. result.m[7] = initialM24;
  5075. result.m[8] = initialM31;
  5076. result.m[9] = initialM32;
  5077. result.m[10] = initialM33;
  5078. result.m[11] = initialM34;
  5079. result.m[12] = initialM41;
  5080. result.m[13] = initialM42;
  5081. result.m[14] = initialM43;
  5082. result.m[15] = initialM44;
  5083. result._markAsUpdated();
  5084. };
  5085. /**
  5086. * Returns the index-th row of the current matrix as a new Vector4.
  5087. */
  5088. Matrix.prototype.getRow = function (index) {
  5089. if (index < 0 || index > 3) {
  5090. return null;
  5091. }
  5092. var i = index * 4;
  5093. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5094. };
  5095. /**
  5096. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5097. * Returns the updated Matrix.
  5098. */
  5099. Matrix.prototype.setRow = function (index, row) {
  5100. if (index < 0 || index > 3) {
  5101. return this;
  5102. }
  5103. var i = index * 4;
  5104. this.m[i + 0] = row.x;
  5105. this.m[i + 1] = row.y;
  5106. this.m[i + 2] = row.z;
  5107. this.m[i + 3] = row.w;
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Compute the transpose of the matrix.
  5113. * Returns a new Matrix.
  5114. */
  5115. Matrix.prototype.transpose = function () {
  5116. return Matrix.Transpose(this);
  5117. };
  5118. /**
  5119. * Compute the transpose of the matrix.
  5120. * Returns the current matrix.
  5121. */
  5122. Matrix.prototype.transposeToRef = function (result) {
  5123. Matrix.TransposeToRef(this, result);
  5124. return this;
  5125. };
  5126. /**
  5127. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5128. * Returns the updated Matrix.
  5129. */
  5130. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5131. if (index < 0 || index > 3) {
  5132. return this;
  5133. }
  5134. var i = index * 4;
  5135. this.m[i + 0] = x;
  5136. this.m[i + 1] = y;
  5137. this.m[i + 2] = z;
  5138. this.m[i + 3] = w;
  5139. this._markAsUpdated();
  5140. return this;
  5141. };
  5142. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5143. /**
  5144. * Static identity matrix to be used as readonly matrix
  5145. * Must not be updated.
  5146. */
  5147. get: function () {
  5148. return Matrix._identityReadOnly;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. /**
  5154. * Returns a new Matrix set from the 16 passed floats.
  5155. */
  5156. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5157. var result = new Matrix();
  5158. result.m[0] = initialM11;
  5159. result.m[1] = initialM12;
  5160. result.m[2] = initialM13;
  5161. result.m[3] = initialM14;
  5162. result.m[4] = initialM21;
  5163. result.m[5] = initialM22;
  5164. result.m[6] = initialM23;
  5165. result.m[7] = initialM24;
  5166. result.m[8] = initialM31;
  5167. result.m[9] = initialM32;
  5168. result.m[10] = initialM33;
  5169. result.m[11] = initialM34;
  5170. result.m[12] = initialM41;
  5171. result.m[13] = initialM42;
  5172. result.m[14] = initialM43;
  5173. result.m[15] = initialM44;
  5174. return result;
  5175. };
  5176. /**
  5177. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5178. */
  5179. Matrix.Compose = function (scale, rotation, translation) {
  5180. var result = Matrix.Identity();
  5181. Matrix.ComposeToRef(scale, rotation, translation, result);
  5182. return result;
  5183. };
  5184. /**
  5185. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5186. */
  5187. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5188. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5189. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5190. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5191. result.setTranslation(translation);
  5192. };
  5193. /**
  5194. * Returns a new indentity Matrix.
  5195. */
  5196. Matrix.Identity = function () {
  5197. 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);
  5198. };
  5199. /**
  5200. * Sets the passed "result" as an identity matrix.
  5201. */
  5202. Matrix.IdentityToRef = function (result) {
  5203. 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);
  5204. };
  5205. /**
  5206. * Returns a new zero Matrix.
  5207. */
  5208. Matrix.Zero = function () {
  5209. 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);
  5210. };
  5211. /**
  5212. * Returns a new rotation matrix for "angle" radians around the X axis.
  5213. */
  5214. Matrix.RotationX = function (angle) {
  5215. var result = new Matrix();
  5216. Matrix.RotationXToRef(angle, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Returns a new Matrix as the passed inverted one.
  5221. */
  5222. Matrix.Invert = function (source) {
  5223. var result = new Matrix();
  5224. source.invertToRef(result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5229. */
  5230. Matrix.RotationXToRef = function (angle, result) {
  5231. var s = Math.sin(angle);
  5232. var c = Math.cos(angle);
  5233. result.m[0] = 1.0;
  5234. result.m[15] = 1.0;
  5235. result.m[5] = c;
  5236. result.m[10] = c;
  5237. result.m[9] = -s;
  5238. result.m[6] = s;
  5239. result.m[1] = 0.0;
  5240. result.m[2] = 0.0;
  5241. result.m[3] = 0.0;
  5242. result.m[4] = 0.0;
  5243. result.m[7] = 0.0;
  5244. result.m[8] = 0.0;
  5245. result.m[11] = 0.0;
  5246. result.m[12] = 0.0;
  5247. result.m[13] = 0.0;
  5248. result.m[14] = 0.0;
  5249. result._markAsUpdated();
  5250. };
  5251. /**
  5252. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5253. */
  5254. Matrix.RotationY = function (angle) {
  5255. var result = new Matrix();
  5256. Matrix.RotationYToRef(angle, result);
  5257. return result;
  5258. };
  5259. /**
  5260. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5261. */
  5262. Matrix.RotationYToRef = function (angle, result) {
  5263. var s = Math.sin(angle);
  5264. var c = Math.cos(angle);
  5265. result.m[5] = 1.0;
  5266. result.m[15] = 1.0;
  5267. result.m[0] = c;
  5268. result.m[2] = -s;
  5269. result.m[8] = s;
  5270. result.m[10] = c;
  5271. result.m[1] = 0.0;
  5272. result.m[3] = 0.0;
  5273. result.m[4] = 0.0;
  5274. result.m[6] = 0.0;
  5275. result.m[7] = 0.0;
  5276. result.m[9] = 0.0;
  5277. result.m[11] = 0.0;
  5278. result.m[12] = 0.0;
  5279. result.m[13] = 0.0;
  5280. result.m[14] = 0.0;
  5281. result._markAsUpdated();
  5282. };
  5283. /**
  5284. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5285. */
  5286. Matrix.RotationZ = function (angle) {
  5287. var result = new Matrix();
  5288. Matrix.RotationZToRef(angle, result);
  5289. return result;
  5290. };
  5291. /**
  5292. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5293. */
  5294. Matrix.RotationZToRef = function (angle, result) {
  5295. var s = Math.sin(angle);
  5296. var c = Math.cos(angle);
  5297. result.m[10] = 1.0;
  5298. result.m[15] = 1.0;
  5299. result.m[0] = c;
  5300. result.m[1] = s;
  5301. result.m[4] = -s;
  5302. result.m[5] = c;
  5303. result.m[2] = 0.0;
  5304. result.m[3] = 0.0;
  5305. result.m[6] = 0.0;
  5306. result.m[7] = 0.0;
  5307. result.m[8] = 0.0;
  5308. result.m[9] = 0.0;
  5309. result.m[11] = 0.0;
  5310. result.m[12] = 0.0;
  5311. result.m[13] = 0.0;
  5312. result.m[14] = 0.0;
  5313. result._markAsUpdated();
  5314. };
  5315. /**
  5316. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5317. */
  5318. Matrix.RotationAxis = function (axis, angle) {
  5319. var result = Matrix.Zero();
  5320. Matrix.RotationAxisToRef(axis, angle, result);
  5321. return result;
  5322. };
  5323. /**
  5324. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5325. */
  5326. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5327. var s = Math.sin(-angle);
  5328. var c = Math.cos(-angle);
  5329. var c1 = 1 - c;
  5330. axis.normalize();
  5331. result.m[0] = (axis.x * axis.x) * c1 + c;
  5332. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5333. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5334. result.m[3] = 0.0;
  5335. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5336. result.m[5] = (axis.y * axis.y) * c1 + c;
  5337. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5338. result.m[7] = 0.0;
  5339. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5340. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5341. result.m[10] = (axis.z * axis.z) * c1 + c;
  5342. result.m[11] = 0.0;
  5343. result.m[15] = 1.0;
  5344. result._markAsUpdated();
  5345. };
  5346. /**
  5347. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5348. */
  5349. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5350. var result = new Matrix();
  5351. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5356. */
  5357. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5358. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5359. this._tempQuaternion.toRotationMatrix(result);
  5360. };
  5361. /**
  5362. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5363. */
  5364. Matrix.Scaling = function (x, y, z) {
  5365. var result = Matrix.Zero();
  5366. Matrix.ScalingToRef(x, y, z, result);
  5367. return result;
  5368. };
  5369. /**
  5370. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5371. */
  5372. Matrix.ScalingToRef = function (x, y, z, result) {
  5373. result.m[0] = x;
  5374. result.m[1] = 0.0;
  5375. result.m[2] = 0.0;
  5376. result.m[3] = 0.0;
  5377. result.m[4] = 0.0;
  5378. result.m[5] = y;
  5379. result.m[6] = 0.0;
  5380. result.m[7] = 0.0;
  5381. result.m[8] = 0.0;
  5382. result.m[9] = 0.0;
  5383. result.m[10] = z;
  5384. result.m[11] = 0.0;
  5385. result.m[12] = 0.0;
  5386. result.m[13] = 0.0;
  5387. result.m[14] = 0.0;
  5388. result.m[15] = 1.0;
  5389. result._markAsUpdated();
  5390. };
  5391. /**
  5392. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5393. */
  5394. Matrix.Translation = function (x, y, z) {
  5395. var result = Matrix.Identity();
  5396. Matrix.TranslationToRef(x, y, z, result);
  5397. return result;
  5398. };
  5399. /**
  5400. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5401. */
  5402. Matrix.TranslationToRef = function (x, y, z, result) {
  5403. 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);
  5404. };
  5405. /**
  5406. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5407. */
  5408. Matrix.Lerp = function (startValue, endValue, gradient) {
  5409. var result = Matrix.Zero();
  5410. for (var index = 0; index < 16; index++) {
  5411. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5412. }
  5413. result._markAsUpdated();
  5414. return result;
  5415. };
  5416. /**
  5417. * Returns a new Matrix whose values are computed by :
  5418. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5419. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5420. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5421. */
  5422. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5423. var startScale = new Vector3(0, 0, 0);
  5424. var startRotation = new Quaternion();
  5425. var startTranslation = new Vector3(0, 0, 0);
  5426. startValue.decompose(startScale, startRotation, startTranslation);
  5427. var endScale = new Vector3(0, 0, 0);
  5428. var endRotation = new Quaternion();
  5429. var endTranslation = new Vector3(0, 0, 0);
  5430. endValue.decompose(endScale, endRotation, endTranslation);
  5431. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5432. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5433. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5434. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5435. };
  5436. /**
  5437. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5438. * This methods works for a Left-Handed system.
  5439. */
  5440. Matrix.LookAtLH = function (eye, target, up) {
  5441. var result = Matrix.Zero();
  5442. Matrix.LookAtLHToRef(eye, target, up, result);
  5443. return result;
  5444. };
  5445. /**
  5446. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5447. * This methods works for a Left-Handed system.
  5448. */
  5449. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5450. // Z axis
  5451. target.subtractToRef(eye, this._zAxis);
  5452. this._zAxis.normalize();
  5453. // X axis
  5454. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5455. if (this._xAxis.lengthSquared() === 0) {
  5456. this._xAxis.x = 1.0;
  5457. }
  5458. else {
  5459. this._xAxis.normalize();
  5460. }
  5461. // Y axis
  5462. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5463. this._yAxis.normalize();
  5464. // Eye angles
  5465. var ex = -Vector3.Dot(this._xAxis, eye);
  5466. var ey = -Vector3.Dot(this._yAxis, eye);
  5467. var ez = -Vector3.Dot(this._zAxis, eye);
  5468. 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);
  5469. };
  5470. /**
  5471. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5472. * This methods works for a Right-Handed system.
  5473. */
  5474. Matrix.LookAtRH = function (eye, target, up) {
  5475. var result = Matrix.Zero();
  5476. Matrix.LookAtRHToRef(eye, target, up, result);
  5477. return result;
  5478. };
  5479. /**
  5480. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5481. * This methods works for a Left-Handed system.
  5482. */
  5483. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5484. // Z axis
  5485. eye.subtractToRef(target, this._zAxis);
  5486. this._zAxis.normalize();
  5487. // X axis
  5488. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5489. if (this._xAxis.lengthSquared() === 0) {
  5490. this._xAxis.x = 1.0;
  5491. }
  5492. else {
  5493. this._xAxis.normalize();
  5494. }
  5495. // Y axis
  5496. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5497. this._yAxis.normalize();
  5498. // Eye angles
  5499. var ex = -Vector3.Dot(this._xAxis, eye);
  5500. var ey = -Vector3.Dot(this._yAxis, eye);
  5501. var ez = -Vector3.Dot(this._zAxis, eye);
  5502. 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);
  5503. };
  5504. /**
  5505. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5506. */
  5507. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5508. var matrix = Matrix.Zero();
  5509. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5510. return matrix;
  5511. };
  5512. /**
  5513. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5514. */
  5515. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5516. var n = znear;
  5517. var f = zfar;
  5518. var a = 2.0 / width;
  5519. var b = 2.0 / height;
  5520. var c = 2.0 / (f - n);
  5521. var d = -(f + n) / (f - n);
  5522. 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);
  5523. };
  5524. /**
  5525. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5526. */
  5527. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5528. var matrix = Matrix.Zero();
  5529. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5530. return matrix;
  5531. };
  5532. /**
  5533. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5534. */
  5535. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5536. var n = znear;
  5537. var f = zfar;
  5538. var a = 2.0 / (right - left);
  5539. var b = 2.0 / (top - bottom);
  5540. var c = 2.0 / (f - n);
  5541. var d = -(f + n) / (f - n);
  5542. var i0 = (left + right) / (left - right);
  5543. var i1 = (top + bottom) / (bottom - top);
  5544. 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);
  5545. };
  5546. /**
  5547. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5548. */
  5549. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5550. var matrix = Matrix.Zero();
  5551. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5552. return matrix;
  5553. };
  5554. /**
  5555. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5556. */
  5557. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5558. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5559. result.m[10] *= -1.0;
  5560. };
  5561. /**
  5562. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5563. */
  5564. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5565. var matrix = Matrix.Zero();
  5566. var n = znear;
  5567. var f = zfar;
  5568. var a = 2.0 * n / width;
  5569. var b = 2.0 * n / height;
  5570. var c = (f + n) / (f - n);
  5571. var d = -2.0 * f * n / (f - n);
  5572. 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);
  5573. return matrix;
  5574. };
  5575. /**
  5576. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5577. */
  5578. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5579. var matrix = Matrix.Zero();
  5580. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5581. return matrix;
  5582. };
  5583. /**
  5584. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5585. */
  5586. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5587. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5588. var n = znear;
  5589. var f = zfar;
  5590. var t = 1.0 / (Math.tan(fov * 0.5));
  5591. var a = isVerticalFovFixed ? (t / aspect) : t;
  5592. var b = isVerticalFovFixed ? t : (t * aspect);
  5593. var c = (f + n) / (f - n);
  5594. var d = -2.0 * f * n / (f - n);
  5595. 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);
  5596. };
  5597. /**
  5598. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5599. */
  5600. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5601. var matrix = Matrix.Zero();
  5602. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5603. return matrix;
  5604. };
  5605. /**
  5606. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5607. */
  5608. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5609. //alternatively this could be expressed as:
  5610. // m = PerspectiveFovLHToRef
  5611. // m[10] *= -1.0;
  5612. // m[11] *= -1.0;
  5613. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5614. var n = znear;
  5615. var f = zfar;
  5616. var t = 1.0 / (Math.tan(fov * 0.5));
  5617. var a = isVerticalFovFixed ? (t / aspect) : t;
  5618. var b = isVerticalFovFixed ? t : (t * aspect);
  5619. var c = -(f + n) / (f - n);
  5620. var d = -2 * f * n / (f - n);
  5621. 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);
  5622. };
  5623. /**
  5624. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5625. */
  5626. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5627. if (rightHanded === void 0) { rightHanded = false; }
  5628. var rightHandedFactor = rightHanded ? -1 : 1;
  5629. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5630. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5631. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5632. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5633. var xScale = 2.0 / (leftTan + rightTan);
  5634. var yScale = 2.0 / (upTan + downTan);
  5635. result.m[0] = xScale;
  5636. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5637. result.m[5] = yScale;
  5638. result.m[6] = result.m[7] = 0.0;
  5639. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5640. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5641. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5642. result.m[10] = -zfar / (znear - zfar);
  5643. result.m[11] = 1.0 * rightHandedFactor;
  5644. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5645. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5646. // result.m[14] = (znear * zfar) / (znear - zfar);
  5647. result._markAsUpdated();
  5648. };
  5649. /**
  5650. * Returns the final transformation matrix : world * view * projection * viewport
  5651. */
  5652. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5653. var cw = viewport.width;
  5654. var ch = viewport.height;
  5655. var cx = viewport.x;
  5656. var cy = viewport.y;
  5657. 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);
  5658. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5659. };
  5660. /**
  5661. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5662. */
  5663. Matrix.GetAsMatrix2x2 = function (matrix) {
  5664. return new Float32Array([
  5665. matrix.m[0], matrix.m[1],
  5666. matrix.m[4], matrix.m[5]
  5667. ]);
  5668. };
  5669. /**
  5670. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5671. */
  5672. Matrix.GetAsMatrix3x3 = function (matrix) {
  5673. return new Float32Array([
  5674. matrix.m[0], matrix.m[1], matrix.m[2],
  5675. matrix.m[4], matrix.m[5], matrix.m[6],
  5676. matrix.m[8], matrix.m[9], matrix.m[10]
  5677. ]);
  5678. };
  5679. /**
  5680. * Compute the transpose of the passed Matrix.
  5681. * Returns a new Matrix.
  5682. */
  5683. Matrix.Transpose = function (matrix) {
  5684. var result = new Matrix();
  5685. Matrix.TransposeToRef(matrix, result);
  5686. return result;
  5687. };
  5688. /**
  5689. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5690. */
  5691. Matrix.TransposeToRef = function (matrix, result) {
  5692. result.m[0] = matrix.m[0];
  5693. result.m[1] = matrix.m[4];
  5694. result.m[2] = matrix.m[8];
  5695. result.m[3] = matrix.m[12];
  5696. result.m[4] = matrix.m[1];
  5697. result.m[5] = matrix.m[5];
  5698. result.m[6] = matrix.m[9];
  5699. result.m[7] = matrix.m[13];
  5700. result.m[8] = matrix.m[2];
  5701. result.m[9] = matrix.m[6];
  5702. result.m[10] = matrix.m[10];
  5703. result.m[11] = matrix.m[14];
  5704. result.m[12] = matrix.m[3];
  5705. result.m[13] = matrix.m[7];
  5706. result.m[14] = matrix.m[11];
  5707. result.m[15] = matrix.m[15];
  5708. };
  5709. /**
  5710. * Returns a new Matrix as the reflection matrix across the passed plane.
  5711. */
  5712. Matrix.Reflection = function (plane) {
  5713. var matrix = new Matrix();
  5714. Matrix.ReflectionToRef(plane, matrix);
  5715. return matrix;
  5716. };
  5717. /**
  5718. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5719. */
  5720. Matrix.ReflectionToRef = function (plane, result) {
  5721. plane.normalize();
  5722. var x = plane.normal.x;
  5723. var y = plane.normal.y;
  5724. var z = plane.normal.z;
  5725. var temp = -2 * x;
  5726. var temp2 = -2 * y;
  5727. var temp3 = -2 * z;
  5728. result.m[0] = (temp * x) + 1;
  5729. result.m[1] = temp2 * x;
  5730. result.m[2] = temp3 * x;
  5731. result.m[3] = 0.0;
  5732. result.m[4] = temp * y;
  5733. result.m[5] = (temp2 * y) + 1;
  5734. result.m[6] = temp3 * y;
  5735. result.m[7] = 0.0;
  5736. result.m[8] = temp * z;
  5737. result.m[9] = temp2 * z;
  5738. result.m[10] = (temp3 * z) + 1;
  5739. result.m[11] = 0.0;
  5740. result.m[12] = temp * plane.d;
  5741. result.m[13] = temp2 * plane.d;
  5742. result.m[14] = temp3 * plane.d;
  5743. result.m[15] = 1.0;
  5744. result._markAsUpdated();
  5745. };
  5746. /**
  5747. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5748. */
  5749. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5750. result.m[0] = xaxis.x;
  5751. result.m[1] = xaxis.y;
  5752. result.m[2] = xaxis.z;
  5753. result.m[3] = 0.0;
  5754. result.m[4] = yaxis.x;
  5755. result.m[5] = yaxis.y;
  5756. result.m[6] = yaxis.z;
  5757. result.m[7] = 0.0;
  5758. result.m[8] = zaxis.x;
  5759. result.m[9] = zaxis.y;
  5760. result.m[10] = zaxis.z;
  5761. result.m[11] = 0.0;
  5762. result.m[12] = 0.0;
  5763. result.m[13] = 0.0;
  5764. result.m[14] = 0.0;
  5765. result.m[15] = 1.0;
  5766. result._markAsUpdated();
  5767. };
  5768. /**
  5769. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5770. */
  5771. Matrix.FromQuaternionToRef = function (quat, result) {
  5772. var xx = quat.x * quat.x;
  5773. var yy = quat.y * quat.y;
  5774. var zz = quat.z * quat.z;
  5775. var xy = quat.x * quat.y;
  5776. var zw = quat.z * quat.w;
  5777. var zx = quat.z * quat.x;
  5778. var yw = quat.y * quat.w;
  5779. var yz = quat.y * quat.z;
  5780. var xw = quat.x * quat.w;
  5781. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5782. result.m[1] = 2.0 * (xy + zw);
  5783. result.m[2] = 2.0 * (zx - yw);
  5784. result.m[3] = 0.0;
  5785. result.m[4] = 2.0 * (xy - zw);
  5786. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5787. result.m[6] = 2.0 * (yz + xw);
  5788. result.m[7] = 0.0;
  5789. result.m[8] = 2.0 * (zx + yw);
  5790. result.m[9] = 2.0 * (yz - xw);
  5791. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5792. result.m[11] = 0.0;
  5793. result.m[12] = 0.0;
  5794. result.m[13] = 0.0;
  5795. result.m[14] = 0.0;
  5796. result.m[15] = 1.0;
  5797. result._markAsUpdated();
  5798. };
  5799. Matrix._tempQuaternion = new Quaternion();
  5800. Matrix._xAxis = Vector3.Zero();
  5801. Matrix._yAxis = Vector3.Zero();
  5802. Matrix._zAxis = Vector3.Zero();
  5803. Matrix._updateFlagSeed = 0;
  5804. Matrix._identityReadOnly = Matrix.Identity();
  5805. return Matrix;
  5806. }());
  5807. BABYLON.Matrix = Matrix;
  5808. var Plane = /** @class */ (function () {
  5809. /**
  5810. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5811. */
  5812. function Plane(a, b, c, d) {
  5813. this.normal = new Vector3(a, b, c);
  5814. this.d = d;
  5815. }
  5816. /**
  5817. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5818. */
  5819. Plane.prototype.asArray = function () {
  5820. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5821. };
  5822. // Methods
  5823. /**
  5824. * Returns a new plane copied from the current Plane.
  5825. */
  5826. Plane.prototype.clone = function () {
  5827. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5828. };
  5829. /**
  5830. * Returns the string "Plane".
  5831. */
  5832. Plane.prototype.getClassName = function () {
  5833. return "Plane";
  5834. };
  5835. /**
  5836. * Returns the Plane hash code.
  5837. */
  5838. Plane.prototype.getHashCode = function () {
  5839. var hash = this.normal.getHashCode();
  5840. hash = (hash * 397) ^ (this.d || 0);
  5841. return hash;
  5842. };
  5843. /**
  5844. * Normalize the current Plane in place.
  5845. * Returns the updated Plane.
  5846. */
  5847. Plane.prototype.normalize = function () {
  5848. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5849. var magnitude = 0.0;
  5850. if (norm !== 0) {
  5851. magnitude = 1.0 / norm;
  5852. }
  5853. this.normal.x *= magnitude;
  5854. this.normal.y *= magnitude;
  5855. this.normal.z *= magnitude;
  5856. this.d *= magnitude;
  5857. return this;
  5858. };
  5859. /**
  5860. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5861. */
  5862. Plane.prototype.transform = function (transformation) {
  5863. var transposedMatrix = Matrix.Transpose(transformation);
  5864. var x = this.normal.x;
  5865. var y = this.normal.y;
  5866. var z = this.normal.z;
  5867. var d = this.d;
  5868. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5869. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5870. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5871. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5872. return new Plane(normalX, normalY, normalZ, finalD);
  5873. };
  5874. /**
  5875. * Returns the dot product (float) of the point coordinates and the plane normal.
  5876. */
  5877. Plane.prototype.dotCoordinate = function (point) {
  5878. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5879. };
  5880. /**
  5881. * Updates the current Plane from the plane defined by the three passed points.
  5882. * Returns the updated Plane.
  5883. */
  5884. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5885. var x1 = point2.x - point1.x;
  5886. var y1 = point2.y - point1.y;
  5887. var z1 = point2.z - point1.z;
  5888. var x2 = point3.x - point1.x;
  5889. var y2 = point3.y - point1.y;
  5890. var z2 = point3.z - point1.z;
  5891. var yz = (y1 * z2) - (z1 * y2);
  5892. var xz = (z1 * x2) - (x1 * z2);
  5893. var xy = (x1 * y2) - (y1 * x2);
  5894. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5895. var invPyth;
  5896. if (pyth !== 0) {
  5897. invPyth = 1.0 / pyth;
  5898. }
  5899. else {
  5900. invPyth = 0.0;
  5901. }
  5902. this.normal.x = yz * invPyth;
  5903. this.normal.y = xz * invPyth;
  5904. this.normal.z = xy * invPyth;
  5905. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5906. return this;
  5907. };
  5908. /**
  5909. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5910. */
  5911. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5912. var dot = Vector3.Dot(this.normal, direction);
  5913. return (dot <= epsilon);
  5914. };
  5915. /**
  5916. * Returns the signed distance (float) from the passed point to the Plane.
  5917. */
  5918. Plane.prototype.signedDistanceTo = function (point) {
  5919. return Vector3.Dot(point, this.normal) + this.d;
  5920. };
  5921. // Statics
  5922. /**
  5923. * Returns a new Plane from the passed array.
  5924. */
  5925. Plane.FromArray = function (array) {
  5926. return new Plane(array[0], array[1], array[2], array[3]);
  5927. };
  5928. /**
  5929. * Returns a new Plane defined by the three passed points.
  5930. */
  5931. Plane.FromPoints = function (point1, point2, point3) {
  5932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5933. result.copyFromPoints(point1, point2, point3);
  5934. return result;
  5935. };
  5936. /**
  5937. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5938. * Note : the vector "normal" is updated because normalized.
  5939. */
  5940. Plane.FromPositionAndNormal = function (origin, normal) {
  5941. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5942. normal.normalize();
  5943. result.normal = normal;
  5944. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5945. return result;
  5946. };
  5947. /**
  5948. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5949. */
  5950. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5951. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5952. return Vector3.Dot(point, normal) + d;
  5953. };
  5954. return Plane;
  5955. }());
  5956. BABYLON.Plane = Plane;
  5957. var Viewport = /** @class */ (function () {
  5958. /**
  5959. * Creates a Viewport object located at (x, y) and sized (width, height).
  5960. */
  5961. function Viewport(x, y, width, height) {
  5962. this.x = x;
  5963. this.y = y;
  5964. this.width = width;
  5965. this.height = height;
  5966. }
  5967. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5968. if (renderWidthOrEngine.getRenderWidth) {
  5969. var engine = renderWidthOrEngine;
  5970. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5971. }
  5972. var renderWidth = renderWidthOrEngine;
  5973. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5974. };
  5975. /**
  5976. * Returns a new Viewport copied from the current one.
  5977. */
  5978. Viewport.prototype.clone = function () {
  5979. return new Viewport(this.x, this.y, this.width, this.height);
  5980. };
  5981. return Viewport;
  5982. }());
  5983. BABYLON.Viewport = Viewport;
  5984. var Frustum = /** @class */ (function () {
  5985. function Frustum() {
  5986. }
  5987. /**
  5988. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5989. */
  5990. Frustum.GetPlanes = function (transform) {
  5991. var frustumPlanes = [];
  5992. for (var index = 0; index < 6; index++) {
  5993. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5994. }
  5995. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5996. return frustumPlanes;
  5997. };
  5998. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5999. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6000. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6001. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6002. frustumPlane.d = transform.m[15] + transform.m[14];
  6003. frustumPlane.normalize();
  6004. };
  6005. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6006. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6007. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6008. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6009. frustumPlane.d = transform.m[15] - transform.m[14];
  6010. frustumPlane.normalize();
  6011. };
  6012. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6013. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6014. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6015. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6016. frustumPlane.d = transform.m[15] + transform.m[12];
  6017. frustumPlane.normalize();
  6018. };
  6019. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6020. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6021. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6022. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6023. frustumPlane.d = transform.m[15] - transform.m[12];
  6024. frustumPlane.normalize();
  6025. };
  6026. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6027. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6028. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6029. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6030. frustumPlane.d = transform.m[15] - transform.m[13];
  6031. frustumPlane.normalize();
  6032. };
  6033. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6034. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6035. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6036. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6037. frustumPlane.d = transform.m[15] + transform.m[13];
  6038. frustumPlane.normalize();
  6039. };
  6040. /**
  6041. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6042. */
  6043. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6044. // Near
  6045. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6046. // Far
  6047. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6048. // Left
  6049. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6050. // Right
  6051. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6052. // Top
  6053. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6054. // Bottom
  6055. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6056. };
  6057. return Frustum;
  6058. }());
  6059. BABYLON.Frustum = Frustum;
  6060. var Space;
  6061. (function (Space) {
  6062. Space[Space["LOCAL"] = 0] = "LOCAL";
  6063. Space[Space["WORLD"] = 1] = "WORLD";
  6064. Space[Space["BONE"] = 2] = "BONE";
  6065. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6066. var Axis = /** @class */ (function () {
  6067. function Axis() {
  6068. }
  6069. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6070. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6071. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6072. return Axis;
  6073. }());
  6074. BABYLON.Axis = Axis;
  6075. ;
  6076. var BezierCurve = /** @class */ (function () {
  6077. function BezierCurve() {
  6078. }
  6079. /**
  6080. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6081. */
  6082. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6083. // Extract X (which is equal to time here)
  6084. var f0 = 1 - 3 * x2 + 3 * x1;
  6085. var f1 = 3 * x2 - 6 * x1;
  6086. var f2 = 3 * x1;
  6087. var refinedT = t;
  6088. for (var i = 0; i < 5; i++) {
  6089. var refinedT2 = refinedT * refinedT;
  6090. var refinedT3 = refinedT2 * refinedT;
  6091. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6092. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6093. refinedT -= (x - t) * slope;
  6094. refinedT = Math.min(1, Math.max(0, refinedT));
  6095. }
  6096. // Resolve cubic bezier for the given x
  6097. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6098. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6099. Math.pow(refinedT, 3);
  6100. };
  6101. return BezierCurve;
  6102. }());
  6103. BABYLON.BezierCurve = BezierCurve;
  6104. var Orientation;
  6105. (function (Orientation) {
  6106. Orientation[Orientation["CW"] = 0] = "CW";
  6107. Orientation[Orientation["CCW"] = 1] = "CCW";
  6108. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6109. var Angle = /** @class */ (function () {
  6110. /**
  6111. * Creates an Angle object of "radians" radians (float).
  6112. */
  6113. function Angle(radians) {
  6114. var _this = this;
  6115. /**
  6116. * Returns the Angle value in degrees (float).
  6117. */
  6118. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6119. /**
  6120. * Returns the Angle value in radians (float).
  6121. */
  6122. this.radians = function () { return _this._radians; };
  6123. this._radians = radians;
  6124. if (this._radians < 0.0)
  6125. this._radians += (2.0 * Math.PI);
  6126. }
  6127. /**
  6128. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6129. */
  6130. Angle.BetweenTwoPoints = function (a, b) {
  6131. var delta = b.subtract(a);
  6132. var theta = Math.atan2(delta.y, delta.x);
  6133. return new Angle(theta);
  6134. };
  6135. /**
  6136. * Returns a new Angle object from the passed float in radians.
  6137. */
  6138. Angle.FromRadians = function (radians) {
  6139. return new Angle(radians);
  6140. };
  6141. /**
  6142. * Returns a new Angle object from the passed float in degrees.
  6143. */
  6144. Angle.FromDegrees = function (degrees) {
  6145. return new Angle(degrees * Math.PI / 180.0);
  6146. };
  6147. return Angle;
  6148. }());
  6149. BABYLON.Angle = Angle;
  6150. var Arc2 = /** @class */ (function () {
  6151. /**
  6152. * Creates an Arc object from the three passed points : start, middle and end.
  6153. */
  6154. function Arc2(startPoint, midPoint, endPoint) {
  6155. this.startPoint = startPoint;
  6156. this.midPoint = midPoint;
  6157. this.endPoint = endPoint;
  6158. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6159. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6160. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6161. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6162. 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);
  6163. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6164. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6165. var a1 = this.startAngle.degrees();
  6166. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6167. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6168. // angles correction
  6169. if (a2 - a1 > +180.0)
  6170. a2 -= 360.0;
  6171. if (a2 - a1 < -180.0)
  6172. a2 += 360.0;
  6173. if (a3 - a2 > +180.0)
  6174. a3 -= 360.0;
  6175. if (a3 - a2 < -180.0)
  6176. a3 += 360.0;
  6177. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6178. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6179. }
  6180. return Arc2;
  6181. }());
  6182. BABYLON.Arc2 = Arc2;
  6183. var Path2 = /** @class */ (function () {
  6184. /**
  6185. * Creates a Path2 object from the starting 2D coordinates x and y.
  6186. */
  6187. function Path2(x, y) {
  6188. this._points = new Array();
  6189. this._length = 0.0;
  6190. this.closed = false;
  6191. this._points.push(new Vector2(x, y));
  6192. }
  6193. /**
  6194. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6195. * Returns the updated Path2.
  6196. */
  6197. Path2.prototype.addLineTo = function (x, y) {
  6198. if (this.closed) {
  6199. return this;
  6200. }
  6201. var newPoint = new Vector2(x, y);
  6202. var previousPoint = this._points[this._points.length - 1];
  6203. this._points.push(newPoint);
  6204. this._length += newPoint.subtract(previousPoint).length();
  6205. return this;
  6206. };
  6207. /**
  6208. * 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.
  6209. * Returns the updated Path2.
  6210. */
  6211. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6212. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6213. if (this.closed) {
  6214. return this;
  6215. }
  6216. var startPoint = this._points[this._points.length - 1];
  6217. var midPoint = new Vector2(midX, midY);
  6218. var endPoint = new Vector2(endX, endY);
  6219. var arc = new Arc2(startPoint, midPoint, endPoint);
  6220. var increment = arc.angle.radians() / numberOfSegments;
  6221. if (arc.orientation === Orientation.CW)
  6222. increment *= -1;
  6223. var currentAngle = arc.startAngle.radians() + increment;
  6224. for (var i = 0; i < numberOfSegments; i++) {
  6225. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6226. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6227. this.addLineTo(x, y);
  6228. currentAngle += increment;
  6229. }
  6230. return this;
  6231. };
  6232. /**
  6233. * Closes the Path2.
  6234. * Returns the Path2.
  6235. */
  6236. Path2.prototype.close = function () {
  6237. this.closed = true;
  6238. return this;
  6239. };
  6240. /**
  6241. * Returns the Path2 total length (float).
  6242. */
  6243. Path2.prototype.length = function () {
  6244. var result = this._length;
  6245. if (!this.closed) {
  6246. var lastPoint = this._points[this._points.length - 1];
  6247. var firstPoint = this._points[0];
  6248. result += (firstPoint.subtract(lastPoint).length());
  6249. }
  6250. return result;
  6251. };
  6252. /**
  6253. * Returns the Path2 internal array of points.
  6254. */
  6255. Path2.prototype.getPoints = function () {
  6256. return this._points;
  6257. };
  6258. /**
  6259. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6260. */
  6261. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6262. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6263. return Vector2.Zero();
  6264. }
  6265. var lengthPosition = normalizedLengthPosition * this.length();
  6266. var previousOffset = 0;
  6267. for (var i = 0; i < this._points.length; i++) {
  6268. var j = (i + 1) % this._points.length;
  6269. var a = this._points[i];
  6270. var b = this._points[j];
  6271. var bToA = b.subtract(a);
  6272. var nextOffset = (bToA.length() + previousOffset);
  6273. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6274. var dir = bToA.normalize();
  6275. var localOffset = lengthPosition - previousOffset;
  6276. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6277. }
  6278. previousOffset = nextOffset;
  6279. }
  6280. return Vector2.Zero();
  6281. };
  6282. /**
  6283. * Returns a new Path2 starting at the coordinates (x, y).
  6284. */
  6285. Path2.StartingAt = function (x, y) {
  6286. return new Path2(x, y);
  6287. };
  6288. return Path2;
  6289. }());
  6290. BABYLON.Path2 = Path2;
  6291. var Path3D = /** @class */ (function () {
  6292. /**
  6293. * new Path3D(path, normal, raw)
  6294. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6295. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6296. * path : an array of Vector3, the curve axis of the Path3D
  6297. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6298. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6299. */
  6300. function Path3D(path, firstNormal, raw) {
  6301. if (firstNormal === void 0) { firstNormal = null; }
  6302. this.path = path;
  6303. this._curve = new Array();
  6304. this._distances = new Array();
  6305. this._tangents = new Array();
  6306. this._normals = new Array();
  6307. this._binormals = new Array();
  6308. for (var p = 0; p < path.length; p++) {
  6309. this._curve[p] = path[p].clone(); // hard copy
  6310. }
  6311. this._raw = raw || false;
  6312. this._compute(firstNormal);
  6313. }
  6314. /**
  6315. * Returns the Path3D array of successive Vector3 designing its curve.
  6316. */
  6317. Path3D.prototype.getCurve = function () {
  6318. return this._curve;
  6319. };
  6320. /**
  6321. * Returns an array populated with tangent vectors on each Path3D curve point.
  6322. */
  6323. Path3D.prototype.getTangents = function () {
  6324. return this._tangents;
  6325. };
  6326. /**
  6327. * Returns an array populated with normal vectors on each Path3D curve point.
  6328. */
  6329. Path3D.prototype.getNormals = function () {
  6330. return this._normals;
  6331. };
  6332. /**
  6333. * Returns an array populated with binormal vectors on each Path3D curve point.
  6334. */
  6335. Path3D.prototype.getBinormals = function () {
  6336. return this._binormals;
  6337. };
  6338. /**
  6339. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6340. */
  6341. Path3D.prototype.getDistances = function () {
  6342. return this._distances;
  6343. };
  6344. /**
  6345. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6346. * Returns the same object updated.
  6347. */
  6348. Path3D.prototype.update = function (path, firstNormal) {
  6349. if (firstNormal === void 0) { firstNormal = null; }
  6350. for (var p = 0; p < path.length; p++) {
  6351. this._curve[p].x = path[p].x;
  6352. this._curve[p].y = path[p].y;
  6353. this._curve[p].z = path[p].z;
  6354. }
  6355. this._compute(firstNormal);
  6356. return this;
  6357. };
  6358. // private function compute() : computes tangents, normals and binormals
  6359. Path3D.prototype._compute = function (firstNormal) {
  6360. var l = this._curve.length;
  6361. // first and last tangents
  6362. this._tangents[0] = this._getFirstNonNullVector(0);
  6363. if (!this._raw) {
  6364. this._tangents[0].normalize();
  6365. }
  6366. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6367. if (!this._raw) {
  6368. this._tangents[l - 1].normalize();
  6369. }
  6370. // normals and binormals at first point : arbitrary vector with _normalVector()
  6371. var tg0 = this._tangents[0];
  6372. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6373. this._normals[0] = pp0;
  6374. if (!this._raw) {
  6375. this._normals[0].normalize();
  6376. }
  6377. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6378. if (!this._raw) {
  6379. this._binormals[0].normalize();
  6380. }
  6381. this._distances[0] = 0.0;
  6382. // normals and binormals : next points
  6383. var prev; // previous vector (segment)
  6384. var cur; // current vector (segment)
  6385. var curTang; // current tangent
  6386. // previous normal
  6387. var prevBinor; // previous binormal
  6388. for (var i = 1; i < l; i++) {
  6389. // tangents
  6390. prev = this._getLastNonNullVector(i);
  6391. if (i < l - 1) {
  6392. cur = this._getFirstNonNullVector(i);
  6393. this._tangents[i] = prev.add(cur);
  6394. this._tangents[i].normalize();
  6395. }
  6396. this._distances[i] = this._distances[i - 1] + prev.length();
  6397. // normals and binormals
  6398. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6399. curTang = this._tangents[i];
  6400. prevBinor = this._binormals[i - 1];
  6401. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6402. if (!this._raw) {
  6403. this._normals[i].normalize();
  6404. }
  6405. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6406. if (!this._raw) {
  6407. this._binormals[i].normalize();
  6408. }
  6409. }
  6410. };
  6411. // private function getFirstNonNullVector(index)
  6412. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6413. Path3D.prototype._getFirstNonNullVector = function (index) {
  6414. var i = 1;
  6415. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6416. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6417. i++;
  6418. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6419. }
  6420. return nNVector;
  6421. };
  6422. // private function getLastNonNullVector(index)
  6423. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6424. Path3D.prototype._getLastNonNullVector = function (index) {
  6425. var i = 1;
  6426. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6427. while (nLVector.length() === 0 && index > i + 1) {
  6428. i++;
  6429. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6430. }
  6431. return nLVector;
  6432. };
  6433. // private function normalVector(v0, vt, va) :
  6434. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6435. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6436. Path3D.prototype._normalVector = function (v0, vt, va) {
  6437. var normal0;
  6438. var tgl = vt.length();
  6439. if (tgl === 0.0) {
  6440. tgl = 1.0;
  6441. }
  6442. if (va === undefined || va === null) {
  6443. var point;
  6444. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6445. point = new Vector3(0.0, -1.0, 0.0);
  6446. }
  6447. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6448. point = new Vector3(1.0, 0.0, 0.0);
  6449. }
  6450. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6451. point = new Vector3(0.0, 0.0, 1.0);
  6452. }
  6453. else {
  6454. point = Vector3.Zero();
  6455. }
  6456. normal0 = Vector3.Cross(vt, point);
  6457. }
  6458. else {
  6459. normal0 = Vector3.Cross(vt, va);
  6460. Vector3.CrossToRef(normal0, vt, normal0);
  6461. }
  6462. normal0.normalize();
  6463. return normal0;
  6464. };
  6465. return Path3D;
  6466. }());
  6467. BABYLON.Path3D = Path3D;
  6468. var Curve3 = /** @class */ (function () {
  6469. /**
  6470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6471. * A Curve3 is designed from a series of successive Vector3.
  6472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6473. */
  6474. function Curve3(points) {
  6475. this._length = 0.0;
  6476. this._points = points;
  6477. this._length = this._computeLength(points);
  6478. }
  6479. /**
  6480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6482. * @param v1 (Vector3) the control point
  6483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6484. * @param nbPoints (integer) the wanted number of points in the curve
  6485. */
  6486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6488. var bez = new Array();
  6489. var equation = function (t, val0, val1, val2) {
  6490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6491. return res;
  6492. };
  6493. for (var i = 0; i <= nbPoints; i++) {
  6494. 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)));
  6495. }
  6496. return new Curve3(bez);
  6497. };
  6498. /**
  6499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6501. * @param v1 (Vector3) the first control point
  6502. * @param v2 (Vector3) the second control point
  6503. * @param v3 (Vector3) the end point of the Cubic Bezier
  6504. * @param nbPoints (integer) the wanted number of points in the curve
  6505. */
  6506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6508. var bez = new Array();
  6509. var equation = function (t, val0, val1, val2, val3) {
  6510. 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;
  6511. return res;
  6512. };
  6513. for (var i = 0; i <= nbPoints; i++) {
  6514. 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)));
  6515. }
  6516. return new Curve3(bez);
  6517. };
  6518. /**
  6519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6520. * @param p1 (Vector3) the origin point of the Hermite Spline
  6521. * @param t1 (Vector3) the tangent vector at the origin point
  6522. * @param p2 (Vector3) the end point of the Hermite Spline
  6523. * @param t2 (Vector3) the tangent vector at the end point
  6524. * @param nbPoints (integer) the wanted number of points in the curve
  6525. */
  6526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6527. var hermite = new Array();
  6528. var step = 1.0 / nbPoints;
  6529. for (var i = 0; i <= nbPoints; i++) {
  6530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6531. }
  6532. return new Curve3(hermite);
  6533. };
  6534. /**
  6535. * Returns a Curve3 object along a CatmullRom Spline curve :
  6536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6538. */
  6539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6540. var totalPoints = new Array();
  6541. totalPoints.push(points[0].clone());
  6542. Array.prototype.push.apply(totalPoints, points);
  6543. totalPoints.push(points[points.length - 1].clone());
  6544. var catmullRom = new Array();
  6545. var step = 1.0 / nbPoints;
  6546. var amount = 0.0;
  6547. for (var i = 0; i < totalPoints.length - 3; i++) {
  6548. amount = 0;
  6549. for (var c = 0; c < nbPoints; c++) {
  6550. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6551. amount += step;
  6552. }
  6553. }
  6554. i--;
  6555. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6556. return new Curve3(catmullRom);
  6557. };
  6558. /**
  6559. * Returns the Curve3 stored array of successive Vector3
  6560. */
  6561. Curve3.prototype.getPoints = function () {
  6562. return this._points;
  6563. };
  6564. /**
  6565. * Returns the computed length (float) of the curve.
  6566. */
  6567. Curve3.prototype.length = function () {
  6568. return this._length;
  6569. };
  6570. /**
  6571. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6572. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6573. * curveA and curveB keep unchanged.
  6574. */
  6575. Curve3.prototype.continue = function (curve) {
  6576. var lastPoint = this._points[this._points.length - 1];
  6577. var continuedPoints = this._points.slice();
  6578. var curvePoints = curve.getPoints();
  6579. for (var i = 1; i < curvePoints.length; i++) {
  6580. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6581. }
  6582. var continuedCurve = new Curve3(continuedPoints);
  6583. return continuedCurve;
  6584. };
  6585. Curve3.prototype._computeLength = function (path) {
  6586. var l = 0;
  6587. for (var i = 1; i < path.length; i++) {
  6588. l += (path[i].subtract(path[i - 1])).length();
  6589. }
  6590. return l;
  6591. };
  6592. return Curve3;
  6593. }());
  6594. BABYLON.Curve3 = Curve3;
  6595. // Vertex formats
  6596. var PositionNormalVertex = /** @class */ (function () {
  6597. function PositionNormalVertex(position, normal) {
  6598. if (position === void 0) { position = Vector3.Zero(); }
  6599. if (normal === void 0) { normal = Vector3.Up(); }
  6600. this.position = position;
  6601. this.normal = normal;
  6602. }
  6603. PositionNormalVertex.prototype.clone = function () {
  6604. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6605. };
  6606. return PositionNormalVertex;
  6607. }());
  6608. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6609. var PositionNormalTextureVertex = /** @class */ (function () {
  6610. function PositionNormalTextureVertex(position, normal, uv) {
  6611. if (position === void 0) { position = Vector3.Zero(); }
  6612. if (normal === void 0) { normal = Vector3.Up(); }
  6613. if (uv === void 0) { uv = Vector2.Zero(); }
  6614. this.position = position;
  6615. this.normal = normal;
  6616. this.uv = uv;
  6617. }
  6618. PositionNormalTextureVertex.prototype.clone = function () {
  6619. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6620. };
  6621. return PositionNormalTextureVertex;
  6622. }());
  6623. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6624. // Temporary pre-allocated objects for engine internal use
  6625. // usage in any internal function :
  6626. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6627. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6628. var Tmp = /** @class */ (function () {
  6629. function Tmp() {
  6630. }
  6631. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6632. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6633. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6634. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6635. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6636. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6637. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6638. Matrix.Zero(), Matrix.Zero(),
  6639. Matrix.Zero(), Matrix.Zero(),
  6640. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6641. return Tmp;
  6642. }());
  6643. BABYLON.Tmp = Tmp;
  6644. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6645. var MathTmp = /** @class */ (function () {
  6646. function MathTmp() {
  6647. }
  6648. MathTmp.Vector3 = [Vector3.Zero()];
  6649. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6650. MathTmp.Quaternion = [Quaternion.Zero()];
  6651. return MathTmp;
  6652. }());
  6653. })(BABYLON || (BABYLON = {}));
  6654. //# sourceMappingURL=babylon.math.js.map
  6655. var BABYLON;
  6656. (function (BABYLON) {
  6657. var Scalar = /** @class */ (function () {
  6658. function Scalar() {
  6659. }
  6660. /**
  6661. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6662. */
  6663. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6664. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6665. var num = a - b;
  6666. return -epsilon <= num && num <= epsilon;
  6667. };
  6668. /**
  6669. * Returns a string : the upper case translation of the number i to hexadecimal.
  6670. */
  6671. Scalar.ToHex = function (i) {
  6672. var str = i.toString(16);
  6673. if (i <= 15) {
  6674. return ("0" + str).toUpperCase();
  6675. }
  6676. return str.toUpperCase();
  6677. };
  6678. /**
  6679. * Returns -1 if value is negative and +1 is value is positive.
  6680. * Returns the value itself if it's equal to zero.
  6681. */
  6682. Scalar.Sign = function (value) {
  6683. value = +value; // convert to a number
  6684. if (value === 0 || isNaN(value))
  6685. return value;
  6686. return value > 0 ? 1 : -1;
  6687. };
  6688. /**
  6689. * Returns the value itself if it's between min and max.
  6690. * Returns min if the value is lower than min.
  6691. * Returns max if the value is greater than max.
  6692. */
  6693. Scalar.Clamp = function (value, min, max) {
  6694. if (min === void 0) { min = 0; }
  6695. if (max === void 0) { max = 1; }
  6696. return Math.min(max, Math.max(min, value));
  6697. };
  6698. /**
  6699. * Returns the log2 of value.
  6700. */
  6701. Scalar.Log2 = function (value) {
  6702. return Math.log(value) * Math.LOG2E;
  6703. };
  6704. /**
  6705. * Loops the value, so that it is never larger than length and never smaller than 0.
  6706. *
  6707. * This is similar to the modulo operator but it works with floating point numbers.
  6708. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6709. * With t = 5 and length = 2.5, the result would be 0.0.
  6710. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6711. */
  6712. Scalar.Repeat = function (value, length) {
  6713. return value - Math.floor(value / length) * length;
  6714. };
  6715. /**
  6716. * Normalize the value between 0.0 and 1.0 using min and max values
  6717. */
  6718. Scalar.Normalize = function (value, min, max) {
  6719. return (value - min) / (max - min);
  6720. };
  6721. /**
  6722. * Denormalize the value from 0.0 and 1.0 using min and max values
  6723. */
  6724. Scalar.Denormalize = function (normalized, min, max) {
  6725. return (normalized * (max - min) + min);
  6726. };
  6727. /**
  6728. * Calculates the shortest difference between two given angles given in degrees.
  6729. */
  6730. Scalar.DeltaAngle = function (current, target) {
  6731. var num = Scalar.Repeat(target - current, 360.0);
  6732. if (num > 180.0) {
  6733. num -= 360.0;
  6734. }
  6735. return num;
  6736. };
  6737. /**
  6738. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6739. *
  6740. * The returned value will move back and forth between 0 and length
  6741. */
  6742. Scalar.PingPong = function (tx, length) {
  6743. var t = Scalar.Repeat(tx, length * 2.0);
  6744. return length - Math.abs(t - length);
  6745. };
  6746. /**
  6747. * Interpolates between min and max with smoothing at the limits.
  6748. *
  6749. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6750. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6751. */
  6752. Scalar.SmoothStep = function (from, to, tx) {
  6753. var t = Scalar.Clamp(tx);
  6754. t = -2.0 * t * t * t + 3.0 * t * t;
  6755. return to * t + from * (1.0 - t);
  6756. };
  6757. /**
  6758. * Moves a value current towards target.
  6759. *
  6760. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6761. * Negative values of maxDelta pushes the value away from target.
  6762. */
  6763. Scalar.MoveTowards = function (current, target, maxDelta) {
  6764. var result = 0;
  6765. if (Math.abs(target - current) <= maxDelta) {
  6766. result = target;
  6767. }
  6768. else {
  6769. result = current + Scalar.Sign(target - current) * maxDelta;
  6770. }
  6771. return result;
  6772. };
  6773. /**
  6774. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6775. *
  6776. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6777. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6778. */
  6779. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6780. var num = Scalar.DeltaAngle(current, target);
  6781. var result = 0;
  6782. if (-maxDelta < num && num < maxDelta) {
  6783. result = target;
  6784. }
  6785. else {
  6786. target = current + num;
  6787. result = Scalar.MoveTowards(current, target, maxDelta);
  6788. }
  6789. return result;
  6790. };
  6791. /**
  6792. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6793. */
  6794. Scalar.Lerp = function (start, end, amount) {
  6795. return start + ((end - start) * amount);
  6796. };
  6797. /**
  6798. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6799. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6800. */
  6801. Scalar.LerpAngle = function (start, end, amount) {
  6802. var num = Scalar.Repeat(end - start, 360.0);
  6803. if (num > 180.0) {
  6804. num -= 360.0;
  6805. }
  6806. return start + num * Scalar.Clamp(amount);
  6807. };
  6808. /**
  6809. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6810. */
  6811. Scalar.InverseLerp = function (a, b, value) {
  6812. var result = 0;
  6813. if (a != b) {
  6814. result = Scalar.Clamp((value - a) / (b - a));
  6815. }
  6816. else {
  6817. result = 0.0;
  6818. }
  6819. return result;
  6820. };
  6821. /**
  6822. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6823. */
  6824. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6825. var squared = amount * amount;
  6826. var cubed = amount * squared;
  6827. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6828. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6829. var part3 = (cubed - (2.0 * squared)) + amount;
  6830. var part4 = cubed - squared;
  6831. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6832. };
  6833. /**
  6834. * Returns a random float number between and min and max values
  6835. */
  6836. Scalar.RandomRange = function (min, max) {
  6837. if (min === max)
  6838. return min;
  6839. return ((Math.random() * (max - min)) + min);
  6840. };
  6841. /**
  6842. * This function returns percentage of a number in a given range.
  6843. *
  6844. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6845. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6846. */
  6847. Scalar.RangeToPercent = function (number, min, max) {
  6848. return ((number - min) / (max - min));
  6849. };
  6850. /**
  6851. * This function returns number that corresponds to the percentage in a given range.
  6852. *
  6853. * PercentToRange(0.34,0,100) will return 34.
  6854. */
  6855. Scalar.PercentToRange = function (percent, min, max) {
  6856. return ((max - min) * percent + min);
  6857. };
  6858. /**
  6859. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6860. * @param angle The angle to normalize in radian.
  6861. * @return The converted angle.
  6862. */
  6863. Scalar.NormalizeRadians = function (angle) {
  6864. // More precise but slower version kept for reference.
  6865. // angle = angle % Tools.TwoPi;
  6866. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6867. //if (angle > Math.PI) {
  6868. // angle -= Tools.TwoPi;
  6869. //}
  6870. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6871. return angle;
  6872. };
  6873. /**
  6874. * Two pi constants convenient for computation.
  6875. */
  6876. Scalar.TwoPi = Math.PI * 2;
  6877. return Scalar;
  6878. }());
  6879. BABYLON.Scalar = Scalar;
  6880. })(BABYLON || (BABYLON = {}));
  6881. //# sourceMappingURL=babylon.math.scalar.js.map
  6882. //# sourceMappingURL=babylon.mixins.js.map
  6883. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6884. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6885. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6886. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6887. //# sourceMappingURL=babylon.webgl2.js.map
  6888. var BABYLON;
  6889. (function (BABYLON) {
  6890. var __decoratorInitialStore = {};
  6891. var __mergedStore = {};
  6892. var _copySource = function (creationFunction, source, instanciate) {
  6893. var destination = creationFunction();
  6894. // Tags
  6895. if (BABYLON.Tags) {
  6896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6897. }
  6898. var classStore = getMergedStore(destination);
  6899. // Properties
  6900. for (var property in classStore) {
  6901. var propertyDescriptor = classStore[property];
  6902. var sourceProperty = source[property];
  6903. var propertyType = propertyDescriptor.type;
  6904. if (sourceProperty !== undefined && sourceProperty !== null) {
  6905. switch (propertyType) {
  6906. case 0: // Value
  6907. case 6:// Mesh reference
  6908. destination[property] = sourceProperty;
  6909. break;
  6910. case 1:// Texture
  6911. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6912. break;
  6913. case 2: // Color3
  6914. case 3: // FresnelParameters
  6915. case 4: // Vector2
  6916. case 5: // Vector3
  6917. case 7: // Color Curves
  6918. case 10:// Quaternion
  6919. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6920. break;
  6921. }
  6922. }
  6923. }
  6924. return destination;
  6925. };
  6926. function getDirectStore(target) {
  6927. var classKey = target.getClassName();
  6928. if (!__decoratorInitialStore[classKey]) {
  6929. __decoratorInitialStore[classKey] = {};
  6930. }
  6931. return __decoratorInitialStore[classKey];
  6932. }
  6933. /**
  6934. * Return the list of properties flagged as serializable
  6935. * @param target: host object
  6936. */
  6937. function getMergedStore(target) {
  6938. var classKey = target.getClassName();
  6939. if (__mergedStore[classKey]) {
  6940. return __mergedStore[classKey];
  6941. }
  6942. __mergedStore[classKey] = {};
  6943. var store = __mergedStore[classKey];
  6944. var currentTarget = target;
  6945. var currentKey = classKey;
  6946. while (currentKey) {
  6947. var initialStore = __decoratorInitialStore[currentKey];
  6948. for (var property in initialStore) {
  6949. store[property] = initialStore[property];
  6950. }
  6951. var parent_1 = void 0;
  6952. var done = false;
  6953. do {
  6954. parent_1 = Object.getPrototypeOf(currentTarget);
  6955. if (!parent_1.getClassName) {
  6956. done = true;
  6957. break;
  6958. }
  6959. if (parent_1.getClassName() !== currentKey) {
  6960. break;
  6961. }
  6962. currentTarget = parent_1;
  6963. } while (parent_1);
  6964. if (done) {
  6965. break;
  6966. }
  6967. currentKey = parent_1.getClassName();
  6968. currentTarget = parent_1;
  6969. }
  6970. return store;
  6971. }
  6972. function generateSerializableMember(type, sourceName) {
  6973. return function (target, propertyKey) {
  6974. var classStore = getDirectStore(target);
  6975. if (!classStore[propertyKey]) {
  6976. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6977. }
  6978. };
  6979. }
  6980. function generateExpandMember(setCallback, targetKey) {
  6981. if (targetKey === void 0) { targetKey = null; }
  6982. return function (target, propertyKey) {
  6983. var key = targetKey || ("_" + propertyKey);
  6984. Object.defineProperty(target, propertyKey, {
  6985. get: function () {
  6986. return this[key];
  6987. },
  6988. set: function (value) {
  6989. if (this[key] === value) {
  6990. return;
  6991. }
  6992. this[key] = value;
  6993. target[setCallback].apply(this);
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. };
  6999. }
  7000. function expandToProperty(callback, targetKey) {
  7001. if (targetKey === void 0) { targetKey = null; }
  7002. return generateExpandMember(callback, targetKey);
  7003. }
  7004. BABYLON.expandToProperty = expandToProperty;
  7005. function serialize(sourceName) {
  7006. return generateSerializableMember(0, sourceName); // value member
  7007. }
  7008. BABYLON.serialize = serialize;
  7009. function serializeAsTexture(sourceName) {
  7010. return generateSerializableMember(1, sourceName); // texture member
  7011. }
  7012. BABYLON.serializeAsTexture = serializeAsTexture;
  7013. function serializeAsColor3(sourceName) {
  7014. return generateSerializableMember(2, sourceName); // color3 member
  7015. }
  7016. BABYLON.serializeAsColor3 = serializeAsColor3;
  7017. function serializeAsFresnelParameters(sourceName) {
  7018. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7019. }
  7020. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7021. function serializeAsVector2(sourceName) {
  7022. return generateSerializableMember(4, sourceName); // vector2 member
  7023. }
  7024. BABYLON.serializeAsVector2 = serializeAsVector2;
  7025. function serializeAsVector3(sourceName) {
  7026. return generateSerializableMember(5, sourceName); // vector3 member
  7027. }
  7028. BABYLON.serializeAsVector3 = serializeAsVector3;
  7029. function serializeAsMeshReference(sourceName) {
  7030. return generateSerializableMember(6, sourceName); // mesh reference member
  7031. }
  7032. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7033. function serializeAsColorCurves(sourceName) {
  7034. return generateSerializableMember(7, sourceName); // color curves
  7035. }
  7036. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7037. function serializeAsColor4(sourceName) {
  7038. return generateSerializableMember(8, sourceName); // color 4
  7039. }
  7040. BABYLON.serializeAsColor4 = serializeAsColor4;
  7041. function serializeAsImageProcessingConfiguration(sourceName) {
  7042. return generateSerializableMember(9, sourceName); // image processing
  7043. }
  7044. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7045. function serializeAsQuaternion(sourceName) {
  7046. return generateSerializableMember(10, sourceName); // quaternion member
  7047. }
  7048. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7049. var SerializationHelper = /** @class */ (function () {
  7050. function SerializationHelper() {
  7051. }
  7052. SerializationHelper.Serialize = function (entity, serializationObject) {
  7053. if (!serializationObject) {
  7054. serializationObject = {};
  7055. }
  7056. // Tags
  7057. if (BABYLON.Tags) {
  7058. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7059. }
  7060. var serializedProperties = getMergedStore(entity);
  7061. // Properties
  7062. for (var property in serializedProperties) {
  7063. var propertyDescriptor = serializedProperties[property];
  7064. var targetPropertyName = propertyDescriptor.sourceName || property;
  7065. var propertyType = propertyDescriptor.type;
  7066. var sourceProperty = entity[property];
  7067. if (sourceProperty !== undefined && sourceProperty !== null) {
  7068. switch (propertyType) {
  7069. case 0:// Value
  7070. serializationObject[targetPropertyName] = sourceProperty;
  7071. break;
  7072. case 1:// Texture
  7073. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7074. break;
  7075. case 2:// Color3
  7076. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7077. break;
  7078. case 3:// FresnelParameters
  7079. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7080. break;
  7081. case 4:// Vector2
  7082. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7083. break;
  7084. case 5:// Vector3
  7085. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7086. break;
  7087. case 6:// Mesh reference
  7088. serializationObject[targetPropertyName] = sourceProperty.id;
  7089. break;
  7090. case 7:// Color Curves
  7091. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7092. break;
  7093. case 8:// Color 4
  7094. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7095. break;
  7096. case 9:// Image Processing
  7097. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7098. break;
  7099. }
  7100. }
  7101. }
  7102. return serializationObject;
  7103. };
  7104. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7105. if (rootUrl === void 0) { rootUrl = null; }
  7106. var destination = creationFunction();
  7107. if (!rootUrl) {
  7108. rootUrl = "";
  7109. }
  7110. // Tags
  7111. if (BABYLON.Tags) {
  7112. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7113. }
  7114. var classStore = getMergedStore(destination);
  7115. // Properties
  7116. for (var property in classStore) {
  7117. var propertyDescriptor = classStore[property];
  7118. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7119. var propertyType = propertyDescriptor.type;
  7120. if (sourceProperty !== undefined && sourceProperty !== null) {
  7121. var dest = destination;
  7122. switch (propertyType) {
  7123. case 0:// Value
  7124. dest[property] = sourceProperty;
  7125. break;
  7126. case 1:// Texture
  7127. if (scene) {
  7128. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7129. }
  7130. break;
  7131. case 2:// Color3
  7132. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7133. break;
  7134. case 3:// FresnelParameters
  7135. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7136. break;
  7137. case 4:// Vector2
  7138. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7139. break;
  7140. case 5:// Vector3
  7141. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7142. break;
  7143. case 6:// Mesh reference
  7144. if (scene) {
  7145. dest[property] = scene.getLastMeshByID(sourceProperty);
  7146. }
  7147. break;
  7148. case 7:// Color Curves
  7149. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7150. break;
  7151. case 8:// Color 4
  7152. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7153. break;
  7154. case 9:// Image Processing
  7155. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7156. break;
  7157. }
  7158. }
  7159. }
  7160. return destination;
  7161. };
  7162. SerializationHelper.Clone = function (creationFunction, source) {
  7163. return _copySource(creationFunction, source, false);
  7164. };
  7165. SerializationHelper.Instanciate = function (creationFunction, source) {
  7166. return _copySource(creationFunction, source, true);
  7167. };
  7168. return SerializationHelper;
  7169. }());
  7170. BABYLON.SerializationHelper = SerializationHelper;
  7171. })(BABYLON || (BABYLON = {}));
  7172. //# sourceMappingURL=babylon.decorators.js.map
  7173. var BABYLON;
  7174. (function (BABYLON) {
  7175. /**
  7176. * Wrapper class for promise with external resolve and reject.
  7177. */
  7178. var Deferred = /** @class */ (function () {
  7179. /**
  7180. * Constructor for this deferred object.
  7181. */
  7182. function Deferred() {
  7183. var _this = this;
  7184. this.promise = new Promise(function (resolve, reject) {
  7185. _this._resolve = resolve;
  7186. _this._reject = reject;
  7187. });
  7188. }
  7189. Object.defineProperty(Deferred.prototype, "resolve", {
  7190. /**
  7191. * The resolve method of the promise associated with this deferred object.
  7192. */
  7193. get: function () {
  7194. return this._resolve;
  7195. },
  7196. enumerable: true,
  7197. configurable: true
  7198. });
  7199. Object.defineProperty(Deferred.prototype, "reject", {
  7200. /**
  7201. * The reject method of the promise associated with this deferred object.
  7202. */
  7203. get: function () {
  7204. return this._reject;
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. return Deferred;
  7210. }());
  7211. BABYLON.Deferred = Deferred;
  7212. })(BABYLON || (BABYLON = {}));
  7213. //# sourceMappingURL=babylon.deferred.js.map
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. /**
  7217. * A class serves as a medium between the observable and its observers
  7218. */
  7219. var EventState = /** @class */ (function () {
  7220. /**
  7221. * Create a new EventState
  7222. * @param mask defines the mask associated with this state
  7223. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7224. * @param target defines the original target of the state
  7225. * @param currentTarget defines the current target of the state
  7226. */
  7227. function EventState(mask, skipNextObservers, target, currentTarget) {
  7228. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7229. this.initalize(mask, skipNextObservers, target, currentTarget);
  7230. }
  7231. /**
  7232. * Initialize the current event state
  7233. * @param mask defines the mask associated with this state
  7234. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7235. * @param target defines the original target of the state
  7236. * @param currentTarget defines the current target of the state
  7237. * @returns the current event state
  7238. */
  7239. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7240. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7241. this.mask = mask;
  7242. this.skipNextObservers = skipNextObservers;
  7243. this.target = target;
  7244. this.currentTarget = currentTarget;
  7245. return this;
  7246. };
  7247. return EventState;
  7248. }());
  7249. BABYLON.EventState = EventState;
  7250. /**
  7251. * Represent an Observer registered to a given Observable object.
  7252. */
  7253. var Observer = /** @class */ (function () {
  7254. /**
  7255. * Creates a new observer
  7256. * @param callback defines the callback to call when the observer is notified
  7257. * @param mask defines the mask of the observer (used to filter notifications)
  7258. * @param scope defines the current scope used to restore the JS context
  7259. */
  7260. function Observer(
  7261. /**
  7262. * Defines the callback to call when the observer is notified
  7263. */
  7264. callback,
  7265. /**
  7266. * Defines the mask of the observer (used to filter notifications)
  7267. */
  7268. mask,
  7269. /**
  7270. * Defines the current scope used to restore the JS context
  7271. */
  7272. scope) {
  7273. if (scope === void 0) { scope = null; }
  7274. this.callback = callback;
  7275. this.mask = mask;
  7276. this.scope = scope;
  7277. /** @ignore */
  7278. this._willBeUnregistered = false;
  7279. /**
  7280. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7281. */
  7282. this.unregisterOnNextCall = false;
  7283. }
  7284. return Observer;
  7285. }());
  7286. BABYLON.Observer = Observer;
  7287. /**
  7288. * Represent a list of observers registered to multiple Observables object.
  7289. */
  7290. var MultiObserver = /** @class */ (function () {
  7291. function MultiObserver() {
  7292. }
  7293. /**
  7294. * Release associated resources
  7295. */
  7296. MultiObserver.prototype.dispose = function () {
  7297. if (this._observers && this._observables) {
  7298. for (var index = 0; index < this._observers.length; index++) {
  7299. this._observables[index].remove(this._observers[index]);
  7300. }
  7301. }
  7302. this._observers = null;
  7303. this._observables = null;
  7304. };
  7305. /**
  7306. * Raise a callback when one of the observable will notify
  7307. * @param observables defines a list of observables to watch
  7308. * @param callback defines the callback to call on notification
  7309. * @param mask defines the mask used to filter notifications
  7310. * @param scope defines the current scope used to restore the JS context
  7311. * @returns the new MultiObserver
  7312. */
  7313. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7314. if (mask === void 0) { mask = -1; }
  7315. if (scope === void 0) { scope = null; }
  7316. var result = new MultiObserver();
  7317. result._observers = new Array();
  7318. result._observables = observables;
  7319. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7320. var observable = observables_1[_i];
  7321. var observer = observable.add(callback, mask, false, scope);
  7322. if (observer) {
  7323. result._observers.push(observer);
  7324. }
  7325. }
  7326. return result;
  7327. };
  7328. return MultiObserver;
  7329. }());
  7330. BABYLON.MultiObserver = MultiObserver;
  7331. /**
  7332. * The Observable class is a simple implementation of the Observable pattern.
  7333. * 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.
  7334. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7335. * 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).
  7336. * 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.
  7337. */
  7338. var Observable = /** @class */ (function () {
  7339. /**
  7340. * Creates a new observable
  7341. * @param onObserverAdded defines a callback to call when a new observer is added
  7342. */
  7343. function Observable(onObserverAdded) {
  7344. this._observers = new Array();
  7345. this._eventState = new EventState(0);
  7346. if (onObserverAdded) {
  7347. this._onObserverAdded = onObserverAdded;
  7348. }
  7349. }
  7350. /**
  7351. * Create a new Observer with the specified callback
  7352. * @param callback the callback that will be executed for that Observer
  7353. * @param mask the mask used to filter observers
  7354. * @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.
  7355. * @param scope optional scope for the callback to be called from
  7356. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7357. * @returns the new observer created for the callback
  7358. */
  7359. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7360. if (mask === void 0) { mask = -1; }
  7361. if (insertFirst === void 0) { insertFirst = false; }
  7362. if (scope === void 0) { scope = null; }
  7363. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7364. if (!callback) {
  7365. return null;
  7366. }
  7367. var observer = new Observer(callback, mask, scope);
  7368. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7369. if (insertFirst) {
  7370. this._observers.unshift(observer);
  7371. }
  7372. else {
  7373. this._observers.push(observer);
  7374. }
  7375. if (this._onObserverAdded) {
  7376. this._onObserverAdded(observer);
  7377. }
  7378. return observer;
  7379. };
  7380. /**
  7381. * Remove an Observer from the Observable object
  7382. * @param observer the instance of the Observer to remove
  7383. * @returns false if it doesn't belong to this Observable
  7384. */
  7385. Observable.prototype.remove = function (observer) {
  7386. if (!observer) {
  7387. return false;
  7388. }
  7389. var index = this._observers.indexOf(observer);
  7390. if (index !== -1) {
  7391. this._observers.splice(index, 1);
  7392. return true;
  7393. }
  7394. return false;
  7395. };
  7396. /**
  7397. * Remove a callback from the Observable object
  7398. * @param callback the callback to remove
  7399. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7400. * @returns false if it doesn't belong to this Observable
  7401. */
  7402. Observable.prototype.removeCallback = function (callback, scope) {
  7403. for (var index = 0; index < this._observers.length; index++) {
  7404. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7405. this._observers.splice(index, 1);
  7406. return true;
  7407. }
  7408. }
  7409. return false;
  7410. };
  7411. Observable.prototype._deferUnregister = function (observer) {
  7412. var _this = this;
  7413. observer.unregisterOnNextCall = false;
  7414. observer._willBeUnregistered = true;
  7415. BABYLON.Tools.SetImmediate(function () {
  7416. _this.remove(observer);
  7417. });
  7418. };
  7419. /**
  7420. * Notify all Observers by calling their respective callback with the given data
  7421. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7422. * @param eventData defines the data to send to all observers
  7423. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7424. * @param target defines the original target of the state
  7425. * @param currentTarget defines the current target of the state
  7426. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7427. */
  7428. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7429. if (mask === void 0) { mask = -1; }
  7430. if (!this._observers.length) {
  7431. return true;
  7432. }
  7433. var state = this._eventState;
  7434. state.mask = mask;
  7435. state.target = target;
  7436. state.currentTarget = currentTarget;
  7437. state.skipNextObservers = false;
  7438. state.lastReturnValue = eventData;
  7439. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7440. var obs = _a[_i];
  7441. if (obs._willBeUnregistered) {
  7442. continue;
  7443. }
  7444. if (obs.mask & mask) {
  7445. if (obs.scope) {
  7446. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7447. }
  7448. else {
  7449. state.lastReturnValue = obs.callback(eventData, state);
  7450. }
  7451. if (obs.unregisterOnNextCall) {
  7452. this._deferUnregister(obs);
  7453. }
  7454. }
  7455. if (state.skipNextObservers) {
  7456. return false;
  7457. }
  7458. }
  7459. return true;
  7460. };
  7461. /**
  7462. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7463. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7464. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7465. * and it is crucial that all callbacks will be executed.
  7466. * The order of the callbacks is kept, callbacks are not executed parallel.
  7467. *
  7468. * @param eventData The data to be sent to each callback
  7469. * @param mask is used to filter observers defaults to -1
  7470. * @param target defines the callback target (see EventState)
  7471. * @param currentTarget defines he current object in the bubbling phase
  7472. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7473. */
  7474. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7475. var _this = this;
  7476. if (mask === void 0) { mask = -1; }
  7477. // create an empty promise
  7478. var p = Promise.resolve(eventData);
  7479. // no observers? return this promise.
  7480. if (!this._observers.length) {
  7481. return p;
  7482. }
  7483. var state = this._eventState;
  7484. state.mask = mask;
  7485. state.target = target;
  7486. state.currentTarget = currentTarget;
  7487. state.skipNextObservers = false;
  7488. // execute one callback after another (not using Promise.all, the order is important)
  7489. this._observers.forEach(function (obs) {
  7490. if (state.skipNextObservers) {
  7491. return;
  7492. }
  7493. if (obs._willBeUnregistered) {
  7494. return;
  7495. }
  7496. if (obs.mask & mask) {
  7497. if (obs.scope) {
  7498. p = p.then(function (lastReturnedValue) {
  7499. state.lastReturnValue = lastReturnedValue;
  7500. return obs.callback.apply(obs.scope, [eventData, state]);
  7501. });
  7502. }
  7503. else {
  7504. p = p.then(function (lastReturnedValue) {
  7505. state.lastReturnValue = lastReturnedValue;
  7506. return obs.callback(eventData, state);
  7507. });
  7508. }
  7509. if (obs.unregisterOnNextCall) {
  7510. _this._deferUnregister(obs);
  7511. }
  7512. }
  7513. });
  7514. // return the eventData
  7515. return p.then(function () { return eventData; });
  7516. };
  7517. /**
  7518. * Notify a specific observer
  7519. * @param observer defines the observer to notify
  7520. * @param eventData defines the data to be sent to each callback
  7521. * @param mask is used to filter observers defaults to -1
  7522. */
  7523. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7524. if (mask === void 0) { mask = -1; }
  7525. var state = this._eventState;
  7526. state.mask = mask;
  7527. state.skipNextObservers = false;
  7528. observer.callback(eventData, state);
  7529. };
  7530. /**
  7531. * Gets a boolean indicating if the observable has at least one observer
  7532. * @returns true is the Observable has at least one Observer registered
  7533. */
  7534. Observable.prototype.hasObservers = function () {
  7535. return this._observers.length > 0;
  7536. };
  7537. /**
  7538. * Clear the list of observers
  7539. */
  7540. Observable.prototype.clear = function () {
  7541. this._observers = new Array();
  7542. this._onObserverAdded = null;
  7543. };
  7544. /**
  7545. * Clone the current observable
  7546. * @returns a new observable
  7547. */
  7548. Observable.prototype.clone = function () {
  7549. var result = new Observable();
  7550. result._observers = this._observers.slice(0);
  7551. return result;
  7552. };
  7553. /**
  7554. * Does this observable handles observer registered with a given mask
  7555. * @param mask defines the mask to be tested
  7556. * @return whether or not one observer registered with the given mask is handeled
  7557. **/
  7558. Observable.prototype.hasSpecificMask = function (mask) {
  7559. if (mask === void 0) { mask = -1; }
  7560. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7561. var obs = _a[_i];
  7562. if (obs.mask & mask || obs.mask === mask) {
  7563. return true;
  7564. }
  7565. }
  7566. return false;
  7567. };
  7568. return Observable;
  7569. }());
  7570. BABYLON.Observable = Observable;
  7571. })(BABYLON || (BABYLON = {}));
  7572. //# sourceMappingURL=babylon.observable.js.map
  7573. var BABYLON;
  7574. (function (BABYLON) {
  7575. var SmartArray = /** @class */ (function () {
  7576. function SmartArray(capacity) {
  7577. this.length = 0;
  7578. this.data = new Array(capacity);
  7579. this._id = SmartArray._GlobalId++;
  7580. }
  7581. SmartArray.prototype.push = function (value) {
  7582. this.data[this.length++] = value;
  7583. if (this.length > this.data.length) {
  7584. this.data.length *= 2;
  7585. }
  7586. };
  7587. SmartArray.prototype.forEach = function (func) {
  7588. for (var index = 0; index < this.length; index++) {
  7589. func(this.data[index]);
  7590. }
  7591. };
  7592. SmartArray.prototype.sort = function (compareFn) {
  7593. this.data.sort(compareFn);
  7594. };
  7595. SmartArray.prototype.reset = function () {
  7596. this.length = 0;
  7597. };
  7598. SmartArray.prototype.dispose = function () {
  7599. this.reset();
  7600. if (this.data) {
  7601. this.data.length = 0;
  7602. this.data = [];
  7603. }
  7604. };
  7605. SmartArray.prototype.concat = function (array) {
  7606. if (array.length === 0) {
  7607. return;
  7608. }
  7609. if (this.length + array.length > this.data.length) {
  7610. this.data.length = (this.length + array.length) * 2;
  7611. }
  7612. for (var index = 0; index < array.length; index++) {
  7613. this.data[this.length++] = (array.data || array)[index];
  7614. }
  7615. };
  7616. SmartArray.prototype.indexOf = function (value) {
  7617. var position = this.data.indexOf(value);
  7618. if (position >= this.length) {
  7619. return -1;
  7620. }
  7621. return position;
  7622. };
  7623. SmartArray.prototype.contains = function (value) {
  7624. return this.data.indexOf(value) !== -1;
  7625. };
  7626. // Statics
  7627. SmartArray._GlobalId = 0;
  7628. return SmartArray;
  7629. }());
  7630. BABYLON.SmartArray = SmartArray;
  7631. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7632. __extends(SmartArrayNoDuplicate, _super);
  7633. function SmartArrayNoDuplicate() {
  7634. var _this = _super !== null && _super.apply(this, arguments) || this;
  7635. _this._duplicateId = 0;
  7636. return _this;
  7637. }
  7638. SmartArrayNoDuplicate.prototype.push = function (value) {
  7639. _super.prototype.push.call(this, value);
  7640. if (!value.__smartArrayFlags) {
  7641. value.__smartArrayFlags = {};
  7642. }
  7643. value.__smartArrayFlags[this._id] = this._duplicateId;
  7644. };
  7645. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7646. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7647. return false;
  7648. }
  7649. this.push(value);
  7650. return true;
  7651. };
  7652. SmartArrayNoDuplicate.prototype.reset = function () {
  7653. _super.prototype.reset.call(this);
  7654. this._duplicateId++;
  7655. };
  7656. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7657. if (array.length === 0) {
  7658. return;
  7659. }
  7660. if (this.length + array.length > this.data.length) {
  7661. this.data.length = (this.length + array.length) * 2;
  7662. }
  7663. for (var index = 0; index < array.length; index++) {
  7664. var item = (array.data || array)[index];
  7665. this.pushNoDuplicate(item);
  7666. }
  7667. };
  7668. return SmartArrayNoDuplicate;
  7669. }(SmartArray));
  7670. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7671. })(BABYLON || (BABYLON = {}));
  7672. //# sourceMappingURL=babylon.smartArray.js.map
  7673. var BABYLON;
  7674. (function (BABYLON) {
  7675. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7676. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7677. var LoadFileError = /** @class */ (function (_super) {
  7678. __extends(LoadFileError, _super);
  7679. function LoadFileError(message, request) {
  7680. var _this = _super.call(this, message) || this;
  7681. _this.request = request;
  7682. _this.name = "LoadFileError";
  7683. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7684. return _this;
  7685. }
  7686. // Polyfill for Object.setPrototypeOf if necessary.
  7687. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7688. return LoadFileError;
  7689. }(Error));
  7690. BABYLON.LoadFileError = LoadFileError;
  7691. var RetryStrategy = /** @class */ (function () {
  7692. function RetryStrategy() {
  7693. }
  7694. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7695. if (maxRetries === void 0) { maxRetries = 3; }
  7696. if (baseInterval === void 0) { baseInterval = 500; }
  7697. return function (url, request, retryIndex) {
  7698. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7699. return -1;
  7700. }
  7701. return Math.pow(2, retryIndex) * baseInterval;
  7702. };
  7703. };
  7704. return RetryStrategy;
  7705. }());
  7706. BABYLON.RetryStrategy = RetryStrategy;
  7707. // Screenshots
  7708. var screenshotCanvas;
  7709. var cloneValue = function (source, destinationObject) {
  7710. if (!source)
  7711. return null;
  7712. if (source instanceof BABYLON.Mesh) {
  7713. return null;
  7714. }
  7715. if (source instanceof BABYLON.SubMesh) {
  7716. return source.clone(destinationObject);
  7717. }
  7718. else if (source.clone) {
  7719. return source.clone();
  7720. }
  7721. return null;
  7722. };
  7723. var Tools = /** @class */ (function () {
  7724. function Tools() {
  7725. }
  7726. /**
  7727. * Interpolates between a and b via alpha
  7728. * @param a The lower value (returned when alpha = 0)
  7729. * @param b The upper value (returned when alpha = 1)
  7730. * @param alpha The interpolation-factor
  7731. * @return The mixed value
  7732. */
  7733. Tools.Mix = function (a, b, alpha) {
  7734. return a * (1 - alpha) + b * alpha;
  7735. };
  7736. Tools.Instantiate = function (className) {
  7737. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7738. return Tools.RegisteredExternalClasses[className];
  7739. }
  7740. var arr = className.split(".");
  7741. var fn = (window || this);
  7742. for (var i = 0, len = arr.length; i < len; i++) {
  7743. fn = fn[arr[i]];
  7744. }
  7745. if (typeof fn !== "function") {
  7746. return null;
  7747. }
  7748. return fn;
  7749. };
  7750. /**
  7751. * Provides a slice function that will work even on IE
  7752. * @param data defines the array to slice
  7753. * @returns the new sliced array
  7754. */
  7755. Tools.Slice = function (data) {
  7756. if (data.slice) {
  7757. return data.slice();
  7758. }
  7759. return Array.prototype.slice.call(data);
  7760. };
  7761. Tools.SetImmediate = function (action) {
  7762. if (window.setImmediate) {
  7763. window.setImmediate(action);
  7764. }
  7765. else {
  7766. setTimeout(action, 1);
  7767. }
  7768. };
  7769. Tools.IsExponentOfTwo = function (value) {
  7770. var count = 1;
  7771. do {
  7772. count *= 2;
  7773. } while (count < value);
  7774. return count === value;
  7775. };
  7776. /**
  7777. * Find the next highest power of two.
  7778. * @param x Number to start search from.
  7779. * @return Next highest power of two.
  7780. */
  7781. Tools.CeilingPOT = function (x) {
  7782. x--;
  7783. x |= x >> 1;
  7784. x |= x >> 2;
  7785. x |= x >> 4;
  7786. x |= x >> 8;
  7787. x |= x >> 16;
  7788. x++;
  7789. return x;
  7790. };
  7791. /**
  7792. * Find the next lowest power of two.
  7793. * @param x Number to start search from.
  7794. * @return Next lowest power of two.
  7795. */
  7796. Tools.FloorPOT = function (x) {
  7797. x = x | (x >> 1);
  7798. x = x | (x >> 2);
  7799. x = x | (x >> 4);
  7800. x = x | (x >> 8);
  7801. x = x | (x >> 16);
  7802. return x - (x >> 1);
  7803. };
  7804. /**
  7805. * Find the nearest power of two.
  7806. * @param x Number to start search from.
  7807. * @return Next nearest power of two.
  7808. */
  7809. Tools.NearestPOT = function (x) {
  7810. var c = Tools.CeilingPOT(x);
  7811. var f = Tools.FloorPOT(x);
  7812. return (c - x) > (x - f) ? f : c;
  7813. };
  7814. Tools.GetExponentOfTwo = function (value, max, mode) {
  7815. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7816. var pot;
  7817. switch (mode) {
  7818. case BABYLON.Engine.SCALEMODE_FLOOR:
  7819. pot = Tools.FloorPOT(value);
  7820. break;
  7821. case BABYLON.Engine.SCALEMODE_NEAREST:
  7822. pot = Tools.NearestPOT(value);
  7823. break;
  7824. case BABYLON.Engine.SCALEMODE_CEILING:
  7825. default:
  7826. pot = Tools.CeilingPOT(value);
  7827. break;
  7828. }
  7829. return Math.min(pot, max);
  7830. };
  7831. Tools.GetFilename = function (path) {
  7832. var index = path.lastIndexOf("/");
  7833. if (index < 0)
  7834. return path;
  7835. return path.substring(index + 1);
  7836. };
  7837. /**
  7838. * Extracts the "folder" part of a path (everything before the filename).
  7839. * @param uri The URI to extract the info from
  7840. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7841. * @returns The "folder" part of the path
  7842. */
  7843. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7844. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7845. var index = uri.lastIndexOf("/");
  7846. if (index < 0) {
  7847. if (returnUnchangedIfNoSlash) {
  7848. return uri;
  7849. }
  7850. return "";
  7851. }
  7852. return uri.substring(0, index + 1);
  7853. };
  7854. Tools.GetDOMTextContent = function (element) {
  7855. var result = "";
  7856. var child = element.firstChild;
  7857. while (child) {
  7858. if (child.nodeType === 3) {
  7859. result += child.textContent;
  7860. }
  7861. child = child.nextSibling;
  7862. }
  7863. return result;
  7864. };
  7865. Tools.ToDegrees = function (angle) {
  7866. return angle * 180 / Math.PI;
  7867. };
  7868. Tools.ToRadians = function (angle) {
  7869. return angle * Math.PI / 180;
  7870. };
  7871. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7872. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7873. var output = "";
  7874. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7875. var i = 0;
  7876. var bytes = new Uint8Array(buffer);
  7877. while (i < bytes.length) {
  7878. chr1 = bytes[i++];
  7879. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7880. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7881. enc1 = chr1 >> 2;
  7882. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7883. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7884. enc4 = chr3 & 63;
  7885. if (isNaN(chr2)) {
  7886. enc3 = enc4 = 64;
  7887. }
  7888. else if (isNaN(chr3)) {
  7889. enc4 = 64;
  7890. }
  7891. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7892. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7893. }
  7894. return "data:image/png;base64," + output;
  7895. };
  7896. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7897. if (bias === void 0) { bias = null; }
  7898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7900. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7901. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7919. if (bias === void 0) { bias = null; }
  7920. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7921. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7922. if (!stride) {
  7923. stride = 3;
  7924. }
  7925. for (var index = start; index < start + count; index++) {
  7926. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7927. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7928. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7929. }
  7930. if (bias) {
  7931. minimum.x -= minimum.x * bias.x + bias.y;
  7932. minimum.y -= minimum.y * bias.x + bias.y;
  7933. minimum.z -= minimum.z * bias.x + bias.y;
  7934. maximum.x += maximum.x * bias.x + bias.y;
  7935. maximum.y += maximum.y * bias.x + bias.y;
  7936. maximum.z += maximum.z * bias.x + bias.y;
  7937. }
  7938. return {
  7939. minimum: minimum,
  7940. maximum: maximum
  7941. };
  7942. };
  7943. Tools.Vector2ArrayFeeder = function (array) {
  7944. return function (index) {
  7945. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7946. var length = isFloatArray ? array.length / 2 : array.length;
  7947. if (index >= length) {
  7948. return null;
  7949. }
  7950. if (isFloatArray) {
  7951. var fa = array;
  7952. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7953. }
  7954. var a = array;
  7955. return a[index];
  7956. };
  7957. };
  7958. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7959. if (bias === void 0) { bias = null; }
  7960. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7961. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7962. var i = 0;
  7963. var cur = feeder(i++);
  7964. while (cur) {
  7965. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7966. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7967. cur = feeder(i++);
  7968. }
  7969. if (bias) {
  7970. minimum.x -= minimum.x * bias.x + bias.y;
  7971. minimum.y -= minimum.y * bias.x + bias.y;
  7972. maximum.x += maximum.x * bias.x + bias.y;
  7973. maximum.y += maximum.y * bias.x + bias.y;
  7974. }
  7975. return {
  7976. minimum: minimum,
  7977. maximum: maximum
  7978. };
  7979. };
  7980. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7981. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7982. return null;
  7983. return Array.isArray(obj) ? obj : [obj];
  7984. };
  7985. // Misc.
  7986. Tools.GetPointerPrefix = function () {
  7987. var eventPrefix = "pointer";
  7988. // Check if pointer events are supported
  7989. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7990. eventPrefix = "mouse";
  7991. }
  7992. return eventPrefix;
  7993. };
  7994. /**
  7995. * @param func - the function to be called
  7996. * @param requester - the object that will request the next frame. Falls back to window.
  7997. */
  7998. Tools.QueueNewFrame = function (func, requester) {
  7999. if (!Tools.IsWindowObjectExist()) {
  8000. return setTimeout(func, 16);
  8001. }
  8002. if (!requester) {
  8003. requester = window;
  8004. }
  8005. if (requester.requestAnimationFrame) {
  8006. return requester.requestAnimationFrame(func);
  8007. }
  8008. else if (requester.msRequestAnimationFrame) {
  8009. return requester.msRequestAnimationFrame(func);
  8010. }
  8011. else if (requester.webkitRequestAnimationFrame) {
  8012. return requester.webkitRequestAnimationFrame(func);
  8013. }
  8014. else if (requester.mozRequestAnimationFrame) {
  8015. return requester.mozRequestAnimationFrame(func);
  8016. }
  8017. else if (requester.oRequestAnimationFrame) {
  8018. return requester.oRequestAnimationFrame(func);
  8019. }
  8020. else {
  8021. return window.setTimeout(func, 16);
  8022. }
  8023. };
  8024. Tools.RequestFullscreen = function (element) {
  8025. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8026. if (!requestFunction)
  8027. return;
  8028. requestFunction.call(element);
  8029. };
  8030. Tools.ExitFullscreen = function () {
  8031. if (document.exitFullscreen) {
  8032. document.exitFullscreen();
  8033. }
  8034. else if (document.mozCancelFullScreen) {
  8035. document.mozCancelFullScreen();
  8036. }
  8037. else if (document.webkitCancelFullScreen) {
  8038. document.webkitCancelFullScreen();
  8039. }
  8040. else if (document.msCancelFullScreen) {
  8041. document.msCancelFullScreen();
  8042. }
  8043. };
  8044. Tools.SetCorsBehavior = function (url, element) {
  8045. if (url && url.indexOf("data:") === 0) {
  8046. return;
  8047. }
  8048. if (Tools.CorsBehavior) {
  8049. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8050. element.crossOrigin = Tools.CorsBehavior;
  8051. }
  8052. else {
  8053. var result = Tools.CorsBehavior(url);
  8054. if (result) {
  8055. element.crossOrigin = result;
  8056. }
  8057. }
  8058. }
  8059. };
  8060. // External files
  8061. Tools.CleanUrl = function (url) {
  8062. url = url.replace(/#/mg, "%23");
  8063. return url;
  8064. };
  8065. Tools.LoadImage = function (url, onLoad, onError, database) {
  8066. if (url instanceof ArrayBuffer) {
  8067. url = Tools.EncodeArrayBufferTobase64(url);
  8068. }
  8069. url = Tools.CleanUrl(url);
  8070. url = Tools.PreprocessUrl(url);
  8071. var img = new Image();
  8072. Tools.SetCorsBehavior(url, img);
  8073. var loadHandler = function () {
  8074. img.removeEventListener("load", loadHandler);
  8075. img.removeEventListener("error", errorHandler);
  8076. onLoad(img);
  8077. };
  8078. var errorHandler = function (err) {
  8079. img.removeEventListener("load", loadHandler);
  8080. img.removeEventListener("error", errorHandler);
  8081. Tools.Error("Error while trying to load image: " + url);
  8082. if (onError) {
  8083. onError("Error while trying to load image: " + url, err);
  8084. }
  8085. };
  8086. img.addEventListener("load", loadHandler);
  8087. img.addEventListener("error", errorHandler);
  8088. var noIndexedDB = function () {
  8089. img.src = url;
  8090. };
  8091. var loadFromIndexedDB = function () {
  8092. if (database) {
  8093. database.loadImageFromDB(url, img);
  8094. }
  8095. };
  8096. //ANY database to do!
  8097. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8098. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8099. }
  8100. else {
  8101. if (url.indexOf("file:") !== -1) {
  8102. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8103. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8104. try {
  8105. var blobURL;
  8106. try {
  8107. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8108. }
  8109. catch (ex) {
  8110. // Chrome doesn't support oneTimeOnly parameter
  8111. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8112. }
  8113. img.src = blobURL;
  8114. }
  8115. catch (e) {
  8116. img.src = "";
  8117. }
  8118. return img;
  8119. }
  8120. }
  8121. noIndexedDB();
  8122. }
  8123. return img;
  8124. };
  8125. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8126. url = Tools.CleanUrl(url);
  8127. url = Tools.PreprocessUrl(url);
  8128. // If file and file input are set
  8129. if (url.indexOf("file:") !== -1) {
  8130. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8131. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8132. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8133. }
  8134. }
  8135. var loadUrl = Tools.BaseUrl + url;
  8136. var aborted = false;
  8137. var fileRequest = {
  8138. onCompleteObservable: new BABYLON.Observable(),
  8139. abort: function () { return aborted = true; },
  8140. };
  8141. var requestFile = function () {
  8142. var request = new XMLHttpRequest();
  8143. var retryHandle = null;
  8144. fileRequest.abort = function () {
  8145. aborted = true;
  8146. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8147. request.abort();
  8148. }
  8149. if (retryHandle !== null) {
  8150. clearTimeout(retryHandle);
  8151. retryHandle = null;
  8152. }
  8153. };
  8154. var retryLoop = function (retryIndex) {
  8155. request.open('GET', loadUrl, true);
  8156. if (useArrayBuffer) {
  8157. request.responseType = "arraybuffer";
  8158. }
  8159. if (onProgress) {
  8160. request.addEventListener("progress", onProgress);
  8161. }
  8162. var onLoadEnd = function () {
  8163. request.removeEventListener("loadend", onLoadEnd);
  8164. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8165. fileRequest.onCompleteObservable.clear();
  8166. };
  8167. request.addEventListener("loadend", onLoadEnd);
  8168. var onReadyStateChange = function () {
  8169. if (aborted) {
  8170. return;
  8171. }
  8172. // In case of undefined state in some browsers.
  8173. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8174. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8175. request.removeEventListener("readystatechange", onReadyStateChange);
  8176. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8177. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8178. return;
  8179. }
  8180. var retryStrategy = Tools.DefaultRetryStrategy;
  8181. if (retryStrategy) {
  8182. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8183. if (waitTime !== -1) {
  8184. // Prevent the request from completing for retry.
  8185. request.removeEventListener("loadend", onLoadEnd);
  8186. request = new XMLHttpRequest();
  8187. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8188. return;
  8189. }
  8190. }
  8191. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8192. if (onError) {
  8193. onError(request, e);
  8194. }
  8195. else {
  8196. throw e;
  8197. }
  8198. }
  8199. };
  8200. request.addEventListener("readystatechange", onReadyStateChange);
  8201. request.send();
  8202. };
  8203. retryLoop(0);
  8204. };
  8205. // Caching all files
  8206. if (database && database.enableSceneOffline) {
  8207. var noIndexedDB_1 = function () {
  8208. if (!aborted) {
  8209. requestFile();
  8210. }
  8211. };
  8212. var loadFromIndexedDB = function () {
  8213. // TODO: database needs to support aborting and should return a IFileRequest
  8214. if (aborted) {
  8215. return;
  8216. }
  8217. if (database) {
  8218. database.loadFileFromDB(url, function (data) {
  8219. if (!aborted) {
  8220. onSuccess(data);
  8221. }
  8222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8223. }, onProgress ? function (event) {
  8224. if (!aborted) {
  8225. onProgress(event);
  8226. }
  8227. } : undefined, noIndexedDB_1, useArrayBuffer);
  8228. }
  8229. };
  8230. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8231. }
  8232. else {
  8233. requestFile();
  8234. }
  8235. return fileRequest;
  8236. };
  8237. /**
  8238. * Load a script (identified by an url). When the url returns, the
  8239. * content of this file is added into a new script element, attached to the DOM (body element)
  8240. */
  8241. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8242. var head = document.getElementsByTagName('head')[0];
  8243. var script = document.createElement('script');
  8244. script.type = 'text/javascript';
  8245. script.src = scriptUrl;
  8246. script.onload = function () {
  8247. if (onSuccess) {
  8248. onSuccess();
  8249. }
  8250. };
  8251. script.onerror = function (e) {
  8252. if (onError) {
  8253. onError("Unable to load script", e);
  8254. }
  8255. };
  8256. head.appendChild(script);
  8257. };
  8258. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8259. var reader = new FileReader();
  8260. var request = {
  8261. onCompleteObservable: new BABYLON.Observable(),
  8262. abort: function () { return reader.abort(); },
  8263. };
  8264. reader.onloadend = function (e) {
  8265. request.onCompleteObservable.notifyObservers(request);
  8266. };
  8267. reader.onload = function (e) {
  8268. //target doesn't have result from ts 1.3
  8269. callback(e.target['result']);
  8270. };
  8271. reader.onprogress = progressCallback;
  8272. reader.readAsDataURL(fileToLoad);
  8273. return request;
  8274. };
  8275. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8276. var reader = new FileReader();
  8277. var request = {
  8278. onCompleteObservable: new BABYLON.Observable(),
  8279. abort: function () { return reader.abort(); },
  8280. };
  8281. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8282. reader.onerror = function (e) {
  8283. Tools.Log("Error while reading file: " + fileToLoad.name);
  8284. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8285. };
  8286. reader.onload = function (e) {
  8287. //target doesn't have result from ts 1.3
  8288. callback(e.target['result']);
  8289. };
  8290. if (progressCallBack) {
  8291. reader.onprogress = progressCallBack;
  8292. }
  8293. if (!useArrayBuffer) {
  8294. // Asynchronous read
  8295. reader.readAsText(fileToLoad);
  8296. }
  8297. else {
  8298. reader.readAsArrayBuffer(fileToLoad);
  8299. }
  8300. return request;
  8301. };
  8302. //returns a downloadable url to a file content.
  8303. Tools.FileAsURL = function (content) {
  8304. var fileBlob = new Blob([content]);
  8305. var url = window.URL || window.webkitURL;
  8306. var link = url.createObjectURL(fileBlob);
  8307. return link;
  8308. };
  8309. // Misc.
  8310. Tools.Format = function (value, decimals) {
  8311. if (decimals === void 0) { decimals = 2; }
  8312. return value.toFixed(decimals);
  8313. };
  8314. Tools.CheckExtends = function (v, min, max) {
  8315. if (v.x < min.x)
  8316. min.x = v.x;
  8317. if (v.y < min.y)
  8318. min.y = v.y;
  8319. if (v.z < min.z)
  8320. min.z = v.z;
  8321. if (v.x > max.x)
  8322. max.x = v.x;
  8323. if (v.y > max.y)
  8324. max.y = v.y;
  8325. if (v.z > max.z)
  8326. max.z = v.z;
  8327. };
  8328. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8329. for (var prop in source) {
  8330. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8331. continue;
  8332. }
  8333. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8334. continue;
  8335. }
  8336. var sourceValue = source[prop];
  8337. var typeOfSourceValue = typeof sourceValue;
  8338. if (typeOfSourceValue === "function") {
  8339. continue;
  8340. }
  8341. if (typeOfSourceValue === "object") {
  8342. if (sourceValue instanceof Array) {
  8343. destination[prop] = [];
  8344. if (sourceValue.length > 0) {
  8345. if (typeof sourceValue[0] == "object") {
  8346. for (var index = 0; index < sourceValue.length; index++) {
  8347. var clonedValue = cloneValue(sourceValue[index], destination);
  8348. if (destination[prop].indexOf(clonedValue) === -1) {
  8349. destination[prop].push(clonedValue);
  8350. }
  8351. }
  8352. }
  8353. else {
  8354. destination[prop] = sourceValue.slice(0);
  8355. }
  8356. }
  8357. }
  8358. else {
  8359. destination[prop] = cloneValue(sourceValue, destination);
  8360. }
  8361. }
  8362. else {
  8363. destination[prop] = sourceValue;
  8364. }
  8365. }
  8366. };
  8367. Tools.IsEmpty = function (obj) {
  8368. for (var i in obj) {
  8369. if (obj.hasOwnProperty(i)) {
  8370. return false;
  8371. }
  8372. }
  8373. return true;
  8374. };
  8375. Tools.RegisterTopRootEvents = function (events) {
  8376. for (var index = 0; index < events.length; index++) {
  8377. var event = events[index];
  8378. window.addEventListener(event.name, event.handler, false);
  8379. try {
  8380. if (window.parent) {
  8381. window.parent.addEventListener(event.name, event.handler, false);
  8382. }
  8383. }
  8384. catch (e) {
  8385. // Silently fails...
  8386. }
  8387. }
  8388. };
  8389. Tools.UnregisterTopRootEvents = function (events) {
  8390. for (var index = 0; index < events.length; index++) {
  8391. var event = events[index];
  8392. window.removeEventListener(event.name, event.handler);
  8393. try {
  8394. if (window.parent) {
  8395. window.parent.removeEventListener(event.name, event.handler);
  8396. }
  8397. }
  8398. catch (e) {
  8399. // Silently fails...
  8400. }
  8401. }
  8402. };
  8403. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8404. if (mimeType === void 0) { mimeType = "image/png"; }
  8405. // Read the contents of the framebuffer
  8406. var numberOfChannelsByLine = width * 4;
  8407. var halfHeight = height / 2;
  8408. //Reading datas from WebGL
  8409. var data = engine.readPixels(0, 0, width, height);
  8410. //To flip image on Y axis.
  8411. for (var i = 0; i < halfHeight; i++) {
  8412. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8413. var currentCell = j + i * numberOfChannelsByLine;
  8414. var targetLine = height - i - 1;
  8415. var targetCell = j + targetLine * numberOfChannelsByLine;
  8416. var temp = data[currentCell];
  8417. data[currentCell] = data[targetCell];
  8418. data[targetCell] = temp;
  8419. }
  8420. }
  8421. // Create a 2D canvas to store the result
  8422. if (!screenshotCanvas) {
  8423. screenshotCanvas = document.createElement('canvas');
  8424. }
  8425. screenshotCanvas.width = width;
  8426. screenshotCanvas.height = height;
  8427. var context = screenshotCanvas.getContext('2d');
  8428. if (context) {
  8429. // Copy the pixels to a 2D canvas
  8430. var imageData = context.createImageData(width, height);
  8431. var castData = (imageData.data);
  8432. castData.set(data);
  8433. context.putImageData(imageData, 0, 0);
  8434. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8435. }
  8436. };
  8437. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8438. if (mimeType === void 0) { mimeType = "image/png"; }
  8439. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8440. if (successCallback) {
  8441. successCallback(base64Image);
  8442. }
  8443. else {
  8444. // We need HTMLCanvasElement.toBlob for HD screenshots
  8445. if (!screenshotCanvas.toBlob) {
  8446. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8447. screenshotCanvas.toBlob = function (callback, type, quality) {
  8448. var _this = this;
  8449. setTimeout(function () {
  8450. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8451. for (var i = 0; i < len; i++) {
  8452. arr[i] = binStr.charCodeAt(i);
  8453. }
  8454. callback(new Blob([arr], { type: type || 'image/png' }));
  8455. });
  8456. };
  8457. }
  8458. screenshotCanvas.toBlob(function (blob) {
  8459. var url = URL.createObjectURL(blob);
  8460. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8461. if (("download" in document.createElement("a"))) {
  8462. var a = window.document.createElement("a");
  8463. a.href = url;
  8464. if (fileName) {
  8465. a.setAttribute("download", fileName);
  8466. }
  8467. else {
  8468. var date = new Date();
  8469. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8470. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8471. }
  8472. window.document.body.appendChild(a);
  8473. a.addEventListener("click", function () {
  8474. if (a.parentElement) {
  8475. a.parentElement.removeChild(a);
  8476. }
  8477. });
  8478. a.click();
  8479. }
  8480. else {
  8481. var newWindow = window.open("");
  8482. if (!newWindow)
  8483. return;
  8484. var img = newWindow.document.createElement("img");
  8485. img.onload = function () {
  8486. // no longer need to read the blob so it's revoked
  8487. URL.revokeObjectURL(url);
  8488. };
  8489. img.src = url;
  8490. newWindow.document.body.appendChild(img);
  8491. }
  8492. });
  8493. }
  8494. };
  8495. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8496. if (mimeType === void 0) { mimeType = "image/png"; }
  8497. var width;
  8498. var height;
  8499. // If a precision value is specified
  8500. if (size.precision) {
  8501. width = Math.round(engine.getRenderWidth() * size.precision);
  8502. height = Math.round(width / engine.getAspectRatio(camera));
  8503. }
  8504. else if (size.width && size.height) {
  8505. width = size.width;
  8506. height = size.height;
  8507. }
  8508. else if (size.width && !size.height) {
  8509. width = size.width;
  8510. height = Math.round(width / engine.getAspectRatio(camera));
  8511. }
  8512. else if (size.height && !size.width) {
  8513. height = size.height;
  8514. width = Math.round(height * engine.getAspectRatio(camera));
  8515. }
  8516. else if (!isNaN(size)) {
  8517. height = size;
  8518. width = size;
  8519. }
  8520. else {
  8521. Tools.Error("Invalid 'size' parameter !");
  8522. return;
  8523. }
  8524. if (!screenshotCanvas) {
  8525. screenshotCanvas = document.createElement('canvas');
  8526. }
  8527. screenshotCanvas.width = width;
  8528. screenshotCanvas.height = height;
  8529. var renderContext = screenshotCanvas.getContext("2d");
  8530. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8531. var newWidth = width;
  8532. var newHeight = newWidth / ratio;
  8533. if (newHeight > height) {
  8534. newHeight = height;
  8535. newWidth = newHeight * ratio;
  8536. }
  8537. var offsetX = Math.max(0, width - newWidth) / 2;
  8538. var offsetY = Math.max(0, height - newHeight) / 2;
  8539. var renderingCanvas = engine.getRenderingCanvas();
  8540. if (renderContext && renderingCanvas) {
  8541. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8542. }
  8543. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8544. };
  8545. /**
  8546. * Generates an image screenshot from the specified camera.
  8547. *
  8548. * @param engine The engine to use for rendering
  8549. * @param camera The camera to use for rendering
  8550. * @param size This parameter can be set to a single number or to an object with the
  8551. * following (optional) properties: precision, width, height. If a single number is passed,
  8552. * it will be used for both width and height. If an object is passed, the screenshot size
  8553. * will be derived from the parameters. The precision property is a multiplier allowing
  8554. * rendering at a higher or lower resolution.
  8555. * @param successCallback The callback receives a single parameter which contains the
  8556. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8557. * src parameter of an <img> to display it.
  8558. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8559. * Check your browser for supported MIME types.
  8560. * @param samples Texture samples (default: 1)
  8561. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8562. * @param fileName A name for for the downloaded file.
  8563. * @constructor
  8564. */
  8565. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8566. if (mimeType === void 0) { mimeType = "image/png"; }
  8567. if (samples === void 0) { samples = 1; }
  8568. if (antialiasing === void 0) { antialiasing = false; }
  8569. var width;
  8570. var height;
  8571. //If a precision value is specified
  8572. if (size.precision) {
  8573. width = Math.round(engine.getRenderWidth() * size.precision);
  8574. height = Math.round(width / engine.getAspectRatio(camera));
  8575. size = { width: width, height: height };
  8576. }
  8577. else if (size.width && size.height) {
  8578. width = size.width;
  8579. height = size.height;
  8580. }
  8581. else if (size.width && !size.height) {
  8582. width = size.width;
  8583. height = Math.round(width / engine.getAspectRatio(camera));
  8584. size = { width: width, height: height };
  8585. }
  8586. else if (size.height && !size.width) {
  8587. height = size.height;
  8588. width = Math.round(height * engine.getAspectRatio(camera));
  8589. size = { width: width, height: height };
  8590. }
  8591. else if (!isNaN(size)) {
  8592. height = size;
  8593. width = size;
  8594. }
  8595. else {
  8596. Tools.Error("Invalid 'size' parameter !");
  8597. return;
  8598. }
  8599. var scene = camera.getScene();
  8600. var previousCamera = null;
  8601. if (scene.activeCamera !== camera) {
  8602. previousCamera = scene.activeCamera;
  8603. scene.activeCamera = camera;
  8604. }
  8605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8607. texture.renderList = null;
  8608. texture.samples = samples;
  8609. if (antialiasing) {
  8610. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8611. }
  8612. texture.onAfterRenderObservable.add(function () {
  8613. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8614. });
  8615. scene.incrementRenderId();
  8616. scene.resetCachedMaterial();
  8617. texture.render(true);
  8618. texture.dispose();
  8619. if (previousCamera) {
  8620. scene.activeCamera = previousCamera;
  8621. }
  8622. camera.getProjectionMatrix(true); // Force cache refresh;
  8623. };
  8624. // XHR response validator for local file scenario
  8625. Tools.ValidateXHRData = function (xhr, dataType) {
  8626. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8627. if (dataType === void 0) { dataType = 7; }
  8628. try {
  8629. if (dataType & 1) {
  8630. if (xhr.responseText && xhr.responseText.length > 0) {
  8631. return true;
  8632. }
  8633. else if (dataType === 1) {
  8634. return false;
  8635. }
  8636. }
  8637. if (dataType & 2) {
  8638. // Check header width and height since there is no "TGA" magic number
  8639. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8640. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8641. return true;
  8642. }
  8643. else if (dataType === 2) {
  8644. return false;
  8645. }
  8646. }
  8647. if (dataType & 4) {
  8648. // Check for the "DDS" magic number
  8649. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8650. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8651. return true;
  8652. }
  8653. else {
  8654. return false;
  8655. }
  8656. }
  8657. }
  8658. catch (e) {
  8659. // Global protection
  8660. }
  8661. return false;
  8662. };
  8663. /**
  8664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8665. * Be aware Math.random() could cause collisions, but:
  8666. * "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"
  8667. */
  8668. Tools.RandomId = function () {
  8669. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8670. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8671. return v.toString(16);
  8672. });
  8673. };
  8674. /**
  8675. * Test if the given uri is a base64 string.
  8676. * @param uri The uri to test
  8677. * @return True if the uri is a base64 string or false otherwise.
  8678. */
  8679. Tools.IsBase64 = function (uri) {
  8680. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8681. };
  8682. /**
  8683. * Decode the given base64 uri.
  8684. * @param uri The uri to decode
  8685. * @return The decoded base64 data.
  8686. */
  8687. Tools.DecodeBase64 = function (uri) {
  8688. var decodedString = atob(uri.split(",")[1]);
  8689. var bufferLength = decodedString.length;
  8690. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8691. for (var i = 0; i < bufferLength; i++) {
  8692. bufferView[i] = decodedString.charCodeAt(i);
  8693. }
  8694. return bufferView.buffer;
  8695. };
  8696. Object.defineProperty(Tools, "NoneLogLevel", {
  8697. get: function () {
  8698. return Tools._NoneLogLevel;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(Tools, "MessageLogLevel", {
  8704. get: function () {
  8705. return Tools._MessageLogLevel;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Tools, "WarningLogLevel", {
  8711. get: function () {
  8712. return Tools._WarningLogLevel;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Object.defineProperty(Tools, "ErrorLogLevel", {
  8718. get: function () {
  8719. return Tools._ErrorLogLevel;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(Tools, "AllLogLevel", {
  8725. get: function () {
  8726. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Tools._AddLogEntry = function (entry) {
  8732. Tools._LogCache = entry + Tools._LogCache;
  8733. if (Tools.OnNewCacheEntry) {
  8734. Tools.OnNewCacheEntry(entry);
  8735. }
  8736. };
  8737. Tools._FormatMessage = function (message) {
  8738. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8739. var date = new Date();
  8740. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8741. };
  8742. Tools._LogDisabled = function (message) {
  8743. // nothing to do
  8744. };
  8745. Tools._LogEnabled = function (message) {
  8746. var formattedMessage = Tools._FormatMessage(message);
  8747. console.log("BJS - " + formattedMessage);
  8748. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8749. Tools._AddLogEntry(entry);
  8750. };
  8751. Tools._WarnDisabled = function (message) {
  8752. // nothing to do
  8753. };
  8754. Tools._WarnEnabled = function (message) {
  8755. var formattedMessage = Tools._FormatMessage(message);
  8756. console.warn("BJS - " + formattedMessage);
  8757. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8758. Tools._AddLogEntry(entry);
  8759. };
  8760. Tools._ErrorDisabled = function (message) {
  8761. // nothing to do
  8762. };
  8763. Tools._ErrorEnabled = function (message) {
  8764. Tools.errorsCount++;
  8765. var formattedMessage = Tools._FormatMessage(message);
  8766. console.error("BJS - " + formattedMessage);
  8767. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8768. Tools._AddLogEntry(entry);
  8769. };
  8770. Object.defineProperty(Tools, "LogCache", {
  8771. get: function () {
  8772. return Tools._LogCache;
  8773. },
  8774. enumerable: true,
  8775. configurable: true
  8776. });
  8777. Tools.ClearLogCache = function () {
  8778. Tools._LogCache = "";
  8779. Tools.errorsCount = 0;
  8780. };
  8781. Object.defineProperty(Tools, "LogLevels", {
  8782. set: function (level) {
  8783. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8784. Tools.Log = Tools._LogEnabled;
  8785. }
  8786. else {
  8787. Tools.Log = Tools._LogDisabled;
  8788. }
  8789. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8790. Tools.Warn = Tools._WarnEnabled;
  8791. }
  8792. else {
  8793. Tools.Warn = Tools._WarnDisabled;
  8794. }
  8795. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8796. Tools.Error = Tools._ErrorEnabled;
  8797. }
  8798. else {
  8799. Tools.Error = Tools._ErrorDisabled;
  8800. }
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Tools.IsWindowObjectExist = function () {
  8806. return (typeof window) !== "undefined";
  8807. };
  8808. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8809. get: function () {
  8810. return Tools._PerformanceNoneLogLevel;
  8811. },
  8812. enumerable: true,
  8813. configurable: true
  8814. });
  8815. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8816. get: function () {
  8817. return Tools._PerformanceUserMarkLogLevel;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8823. get: function () {
  8824. return Tools._PerformanceConsoleLogLevel;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8830. set: function (level) {
  8831. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8832. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8833. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8834. return;
  8835. }
  8836. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8837. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8838. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8839. return;
  8840. }
  8841. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8842. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8848. };
  8849. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8850. };
  8851. Tools._StartUserMark = function (counterName, condition) {
  8852. if (condition === void 0) { condition = true; }
  8853. if (!Tools._performance) {
  8854. if (!Tools.IsWindowObjectExist()) {
  8855. return;
  8856. }
  8857. Tools._performance = window.performance;
  8858. }
  8859. if (!condition || !Tools._performance.mark) {
  8860. return;
  8861. }
  8862. Tools._performance.mark(counterName + "-Begin");
  8863. };
  8864. Tools._EndUserMark = function (counterName, condition) {
  8865. if (condition === void 0) { condition = true; }
  8866. if (!condition || !Tools._performance.mark) {
  8867. return;
  8868. }
  8869. Tools._performance.mark(counterName + "-End");
  8870. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8871. };
  8872. Tools._StartPerformanceConsole = function (counterName, condition) {
  8873. if (condition === void 0) { condition = true; }
  8874. if (!condition) {
  8875. return;
  8876. }
  8877. Tools._StartUserMark(counterName, condition);
  8878. if (console.time) {
  8879. console.time(counterName);
  8880. }
  8881. };
  8882. Tools._EndPerformanceConsole = function (counterName, condition) {
  8883. if (condition === void 0) { condition = true; }
  8884. if (!condition) {
  8885. return;
  8886. }
  8887. Tools._EndUserMark(counterName, condition);
  8888. if (console.time) {
  8889. console.timeEnd(counterName);
  8890. }
  8891. };
  8892. Object.defineProperty(Tools, "Now", {
  8893. get: function () {
  8894. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8895. return window.performance.now();
  8896. }
  8897. return new Date().getTime();
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. /**
  8903. * This method will return the name of the class used to create the instance of the given object.
  8904. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8905. * @param object the object to get the class name from
  8906. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8907. */
  8908. Tools.GetClassName = function (object, isType) {
  8909. if (isType === void 0) { isType = false; }
  8910. var name = null;
  8911. if (!isType && object.getClassName) {
  8912. name = object.getClassName();
  8913. }
  8914. else {
  8915. if (object instanceof Object) {
  8916. var classObj = isType ? object : Object.getPrototypeOf(object);
  8917. name = classObj.constructor["__bjsclassName__"];
  8918. }
  8919. if (!name) {
  8920. name = typeof object;
  8921. }
  8922. }
  8923. return name;
  8924. };
  8925. Tools.First = function (array, predicate) {
  8926. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8927. var el = array_1[_i];
  8928. if (predicate(el)) {
  8929. return el;
  8930. }
  8931. }
  8932. return null;
  8933. };
  8934. /**
  8935. * This method will return the name of the full name of the class, including its owning module (if any).
  8936. * 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).
  8937. * @param object the object to get the class name from
  8938. * @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.
  8939. */
  8940. Tools.getFullClassName = function (object, isType) {
  8941. if (isType === void 0) { isType = false; }
  8942. var className = null;
  8943. var moduleName = null;
  8944. if (!isType && object.getClassName) {
  8945. className = object.getClassName();
  8946. }
  8947. else {
  8948. if (object instanceof Object) {
  8949. var classObj = isType ? object : Object.getPrototypeOf(object);
  8950. className = classObj.constructor["__bjsclassName__"];
  8951. moduleName = classObj.constructor["__bjsmoduleName__"];
  8952. }
  8953. if (!className) {
  8954. className = typeof object;
  8955. }
  8956. }
  8957. if (!className) {
  8958. return null;
  8959. }
  8960. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8961. };
  8962. /**
  8963. * 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.
  8964. * @param array
  8965. */
  8966. Tools.arrayOrStringFeeder = function (array) {
  8967. return function (index) {
  8968. if (index >= array.length) {
  8969. return null;
  8970. }
  8971. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8972. if (val && val.getHashCode) {
  8973. val = val.getHashCode();
  8974. }
  8975. if (typeof val === "string") {
  8976. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8977. }
  8978. return val;
  8979. };
  8980. };
  8981. /**
  8982. * Compute the hashCode of a stream of number
  8983. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8984. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8985. * @return the hash code computed
  8986. */
  8987. Tools.hashCodeFromStream = function (feeder) {
  8988. // Based from here: http://stackoverflow.com/a/7616484/802124
  8989. var hash = 0;
  8990. var index = 0;
  8991. var chr = feeder(index++);
  8992. while (chr != null) {
  8993. hash = ((hash << 5) - hash) + chr;
  8994. hash |= 0; // Convert to 32bit integer
  8995. chr = feeder(index++);
  8996. }
  8997. return hash;
  8998. };
  8999. /**
  9000. * Returns a promise that resolves after the given amount of time.
  9001. * @param delay Number of milliseconds to delay
  9002. * @returns Promise that resolves after the given amount of time
  9003. */
  9004. Tools.DelayAsync = function (delay) {
  9005. return new Promise(function (resolve) {
  9006. setTimeout(function () {
  9007. resolve();
  9008. }, delay);
  9009. });
  9010. };
  9011. Tools.BaseUrl = "";
  9012. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9013. /**
  9014. * Default behaviour for cors in the application.
  9015. * It can be a string if the expected behavior is identical in the entire app.
  9016. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9017. */
  9018. Tools.CorsBehavior = "anonymous";
  9019. Tools.UseFallbackTexture = true;
  9020. /**
  9021. * Use this object to register external classes like custom textures or material
  9022. * to allow the laoders to instantiate them
  9023. */
  9024. Tools.RegisteredExternalClasses = {};
  9025. // Used in case of a texture loading problem
  9026. 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";
  9027. Tools.PreprocessUrl = function (url) {
  9028. return url;
  9029. };
  9030. // Logs
  9031. Tools._NoneLogLevel = 0;
  9032. Tools._MessageLogLevel = 1;
  9033. Tools._WarningLogLevel = 2;
  9034. Tools._ErrorLogLevel = 4;
  9035. Tools._LogCache = "";
  9036. Tools.errorsCount = 0;
  9037. Tools.Log = Tools._LogEnabled;
  9038. Tools.Warn = Tools._WarnEnabled;
  9039. Tools.Error = Tools._ErrorEnabled;
  9040. // Performances
  9041. Tools._PerformanceNoneLogLevel = 0;
  9042. Tools._PerformanceUserMarkLogLevel = 1;
  9043. Tools._PerformanceConsoleLogLevel = 2;
  9044. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9045. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9046. return Tools;
  9047. }());
  9048. BABYLON.Tools = Tools;
  9049. /**
  9050. * This class is used to track a performance counter which is number based.
  9051. * The user has access to many properties which give statistics of different nature
  9052. *
  9053. * The implementer can track two kinds of Performance Counter: time and count
  9054. * 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.
  9055. * 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.
  9056. */
  9057. var PerfCounter = /** @class */ (function () {
  9058. function PerfCounter() {
  9059. this._startMonitoringTime = 0;
  9060. this._min = 0;
  9061. this._max = 0;
  9062. this._average = 0;
  9063. this._lastSecAverage = 0;
  9064. this._current = 0;
  9065. this._totalValueCount = 0;
  9066. this._totalAccumulated = 0;
  9067. this._lastSecAccumulated = 0;
  9068. this._lastSecTime = 0;
  9069. this._lastSecValueCount = 0;
  9070. }
  9071. Object.defineProperty(PerfCounter.prototype, "min", {
  9072. /**
  9073. * Returns the smallest value ever
  9074. */
  9075. get: function () {
  9076. return this._min;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(PerfCounter.prototype, "max", {
  9082. /**
  9083. * Returns the biggest value ever
  9084. */
  9085. get: function () {
  9086. return this._max;
  9087. },
  9088. enumerable: true,
  9089. configurable: true
  9090. });
  9091. Object.defineProperty(PerfCounter.prototype, "average", {
  9092. /**
  9093. * Returns the average value since the performance counter is running
  9094. */
  9095. get: function () {
  9096. return this._average;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9102. /**
  9103. * Returns the average value of the last second the counter was monitored
  9104. */
  9105. get: function () {
  9106. return this._lastSecAverage;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(PerfCounter.prototype, "current", {
  9112. /**
  9113. * Returns the current value
  9114. */
  9115. get: function () {
  9116. return this._current;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(PerfCounter.prototype, "total", {
  9122. get: function () {
  9123. return this._totalAccumulated;
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. Object.defineProperty(PerfCounter.prototype, "count", {
  9129. get: function () {
  9130. return this._totalValueCount;
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. /**
  9136. * Call this method to start monitoring a new frame.
  9137. * 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.
  9138. */
  9139. PerfCounter.prototype.fetchNewFrame = function () {
  9140. this._totalValueCount++;
  9141. this._current = 0;
  9142. this._lastSecValueCount++;
  9143. };
  9144. /**
  9145. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9146. * @param newCount the count value to add to the monitored count
  9147. * @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.
  9148. */
  9149. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9150. if (!PerfCounter.Enabled) {
  9151. return;
  9152. }
  9153. this._current += newCount;
  9154. if (fetchResult) {
  9155. this._fetchResult();
  9156. }
  9157. };
  9158. /**
  9159. * Start monitoring this performance counter
  9160. */
  9161. PerfCounter.prototype.beginMonitoring = function () {
  9162. if (!PerfCounter.Enabled) {
  9163. return;
  9164. }
  9165. this._startMonitoringTime = Tools.Now;
  9166. };
  9167. /**
  9168. * Compute the time lapsed since the previous beginMonitoring() call.
  9169. * @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
  9170. */
  9171. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9172. if (newFrame === void 0) { newFrame = true; }
  9173. if (!PerfCounter.Enabled) {
  9174. return;
  9175. }
  9176. if (newFrame) {
  9177. this.fetchNewFrame();
  9178. }
  9179. var currentTime = Tools.Now;
  9180. this._current = currentTime - this._startMonitoringTime;
  9181. if (newFrame) {
  9182. this._fetchResult();
  9183. }
  9184. };
  9185. PerfCounter.prototype._fetchResult = function () {
  9186. this._totalAccumulated += this._current;
  9187. this._lastSecAccumulated += this._current;
  9188. // Min/Max update
  9189. this._min = Math.min(this._min, this._current);
  9190. this._max = Math.max(this._max, this._current);
  9191. this._average = this._totalAccumulated / this._totalValueCount;
  9192. // Reset last sec?
  9193. var now = Tools.Now;
  9194. if ((now - this._lastSecTime) > 1000) {
  9195. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9196. this._lastSecTime = now;
  9197. this._lastSecAccumulated = 0;
  9198. this._lastSecValueCount = 0;
  9199. }
  9200. };
  9201. PerfCounter.Enabled = true;
  9202. return PerfCounter;
  9203. }());
  9204. BABYLON.PerfCounter = PerfCounter;
  9205. /**
  9206. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9207. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9208. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9209. * @param name The name of the class, case should be preserved
  9210. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9211. */
  9212. function className(name, module) {
  9213. return function (target) {
  9214. target["__bjsclassName__"] = name;
  9215. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9216. };
  9217. }
  9218. BABYLON.className = className;
  9219. /**
  9220. * An implementation of a loop for asynchronous functions.
  9221. */
  9222. var AsyncLoop = /** @class */ (function () {
  9223. /**
  9224. * Constroctor.
  9225. * @param iterations the number of iterations.
  9226. * @param _fn the function to run each iteration
  9227. * @param _successCallback the callback that will be called upon succesful execution
  9228. * @param offset starting offset.
  9229. */
  9230. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9231. if (offset === void 0) { offset = 0; }
  9232. this.iterations = iterations;
  9233. this._fn = _fn;
  9234. this._successCallback = _successCallback;
  9235. this.index = offset - 1;
  9236. this._done = false;
  9237. }
  9238. /**
  9239. * Execute the next iteration. Must be called after the last iteration was finished.
  9240. */
  9241. AsyncLoop.prototype.executeNext = function () {
  9242. if (!this._done) {
  9243. if (this.index + 1 < this.iterations) {
  9244. ++this.index;
  9245. this._fn(this);
  9246. }
  9247. else {
  9248. this.breakLoop();
  9249. }
  9250. }
  9251. };
  9252. /**
  9253. * Break the loop and run the success callback.
  9254. */
  9255. AsyncLoop.prototype.breakLoop = function () {
  9256. this._done = true;
  9257. this._successCallback();
  9258. };
  9259. /**
  9260. * Helper function
  9261. */
  9262. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9263. if (offset === void 0) { offset = 0; }
  9264. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9265. loop.executeNext();
  9266. return loop;
  9267. };
  9268. /**
  9269. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9270. * @param iterations total number of iterations
  9271. * @param syncedIterations number of synchronous iterations in each async iteration.
  9272. * @param fn the function to call each iteration.
  9273. * @param callback a success call back that will be called when iterating stops.
  9274. * @param breakFunction a break condition (optional)
  9275. * @param timeout timeout settings for the setTimeout function. default - 0.
  9276. * @constructor
  9277. */
  9278. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9279. if (timeout === void 0) { timeout = 0; }
  9280. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9281. if (breakFunction && breakFunction())
  9282. loop.breakLoop();
  9283. else {
  9284. setTimeout(function () {
  9285. for (var i = 0; i < syncedIterations; ++i) {
  9286. var iteration = (loop.index * syncedIterations) + i;
  9287. if (iteration >= iterations)
  9288. break;
  9289. fn(iteration);
  9290. if (breakFunction && breakFunction()) {
  9291. loop.breakLoop();
  9292. break;
  9293. }
  9294. }
  9295. loop.executeNext();
  9296. }, timeout);
  9297. }
  9298. }, callback);
  9299. };
  9300. return AsyncLoop;
  9301. }());
  9302. BABYLON.AsyncLoop = AsyncLoop;
  9303. })(BABYLON || (BABYLON = {}));
  9304. //# sourceMappingURL=babylon.tools.js.map
  9305. var BABYLON;
  9306. (function (BABYLON) {
  9307. var PromiseStates;
  9308. (function (PromiseStates) {
  9309. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9310. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9311. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9312. })(PromiseStates || (PromiseStates = {}));
  9313. var FulFillmentAgregator = /** @class */ (function () {
  9314. function FulFillmentAgregator() {
  9315. this.count = 0;
  9316. this.target = 0;
  9317. this.results = [];
  9318. }
  9319. return FulFillmentAgregator;
  9320. }());
  9321. var InternalPromise = /** @class */ (function () {
  9322. function InternalPromise(resolver) {
  9323. var _this = this;
  9324. this._state = PromiseStates.Pending;
  9325. this._children = new Array();
  9326. this._rejectWasConsumed = false;
  9327. if (!resolver) {
  9328. return;
  9329. }
  9330. try {
  9331. resolver(function (value) {
  9332. _this._resolve(value);
  9333. }, function (reason) {
  9334. _this._reject(reason);
  9335. });
  9336. }
  9337. catch (e) {
  9338. this._reject(e);
  9339. }
  9340. }
  9341. InternalPromise.prototype.catch = function (onRejected) {
  9342. return this.then(undefined, onRejected);
  9343. };
  9344. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9345. var _this = this;
  9346. var newPromise = new InternalPromise();
  9347. newPromise._onFulfilled = onFulfilled;
  9348. newPromise._onRejected = onRejected;
  9349. // Composition
  9350. this._children.push(newPromise);
  9351. if (this._state !== PromiseStates.Pending) {
  9352. BABYLON.Tools.SetImmediate(function () {
  9353. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9354. var returnedValue = newPromise._resolve(_this._result);
  9355. if (returnedValue !== undefined && returnedValue !== null) {
  9356. if (returnedValue._state !== undefined) {
  9357. var returnedPromise = returnedValue;
  9358. newPromise._children.push(returnedPromise);
  9359. newPromise = returnedPromise;
  9360. }
  9361. else {
  9362. newPromise._result = returnedValue;
  9363. }
  9364. }
  9365. }
  9366. else {
  9367. newPromise._reject(_this._reason);
  9368. }
  9369. });
  9370. }
  9371. return newPromise;
  9372. };
  9373. InternalPromise.prototype._moveChildren = function (children) {
  9374. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9375. if (this._state === PromiseStates.Fulfilled) {
  9376. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9377. var child = _b[_i];
  9378. child._resolve(this._result);
  9379. }
  9380. }
  9381. else if (this._state === PromiseStates.Rejected) {
  9382. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9383. var child = _d[_c];
  9384. child._reject(this._reason);
  9385. }
  9386. }
  9387. var _a;
  9388. };
  9389. InternalPromise.prototype._resolve = function (value) {
  9390. try {
  9391. this._state = PromiseStates.Fulfilled;
  9392. this._result = value;
  9393. var returnedValue = null;
  9394. if (this._onFulfilled) {
  9395. returnedValue = this._onFulfilled(value);
  9396. }
  9397. if (returnedValue !== undefined && returnedValue !== null) {
  9398. if (returnedValue._state !== undefined) {
  9399. // Transmit children
  9400. var returnedPromise = returnedValue;
  9401. returnedPromise._moveChildren(this._children);
  9402. }
  9403. else {
  9404. value = returnedValue;
  9405. }
  9406. }
  9407. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9408. var child = _a[_i];
  9409. child._resolve(value);
  9410. }
  9411. this._children.length = 0;
  9412. delete this._onFulfilled;
  9413. delete this._onRejected;
  9414. return returnedValue;
  9415. }
  9416. catch (e) {
  9417. this._reject(e, true);
  9418. }
  9419. return null;
  9420. };
  9421. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9422. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9423. this._state = PromiseStates.Rejected;
  9424. this._reason = reason;
  9425. if (this._onRejected && !onLocalThrow) {
  9426. try {
  9427. this._onRejected(reason);
  9428. this._rejectWasConsumed = true;
  9429. }
  9430. catch (e) {
  9431. reason = e;
  9432. }
  9433. }
  9434. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9435. var child = _a[_i];
  9436. if (this._rejectWasConsumed) {
  9437. child._resolve(null);
  9438. }
  9439. else {
  9440. child._reject(reason);
  9441. }
  9442. }
  9443. this._children.length = 0;
  9444. delete this._onFulfilled;
  9445. delete this._onRejected;
  9446. };
  9447. InternalPromise.resolve = function (value) {
  9448. var newPromise = new InternalPromise();
  9449. newPromise._resolve(value);
  9450. return newPromise;
  9451. };
  9452. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9453. promise.then(function (value) {
  9454. agregator.results[index] = value;
  9455. agregator.count++;
  9456. if (agregator.count === agregator.target) {
  9457. agregator.rootPromise._resolve(agregator.results);
  9458. }
  9459. return null;
  9460. }, function (reason) {
  9461. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9462. agregator.rootPromise._reject(reason);
  9463. }
  9464. });
  9465. };
  9466. InternalPromise.all = function (promises) {
  9467. var newPromise = new InternalPromise();
  9468. var agregator = new FulFillmentAgregator();
  9469. agregator.target = promises.length;
  9470. agregator.rootPromise = newPromise;
  9471. if (promises.length) {
  9472. for (var index = 0; index < promises.length; index++) {
  9473. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9474. }
  9475. }
  9476. else {
  9477. newPromise._resolve([]);
  9478. }
  9479. return newPromise;
  9480. };
  9481. return InternalPromise;
  9482. }());
  9483. /**
  9484. * Helper class that provides a small promise polyfill
  9485. */
  9486. var PromisePolyfill = /** @class */ (function () {
  9487. function PromisePolyfill() {
  9488. }
  9489. /**
  9490. * Static function used to check if the polyfill is required
  9491. * If this is the case then the function will inject the polyfill to window.Promise
  9492. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9493. */
  9494. PromisePolyfill.Apply = function (force) {
  9495. if (force === void 0) { force = false; }
  9496. if (force || typeof Promise === 'undefined') {
  9497. var root = window;
  9498. root.Promise = InternalPromise;
  9499. }
  9500. };
  9501. return PromisePolyfill;
  9502. }());
  9503. BABYLON.PromisePolyfill = PromisePolyfill;
  9504. })(BABYLON || (BABYLON = {}));
  9505. //# sourceMappingURL=babylon.promise.js.map
  9506. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9507. var BABYLON;
  9508. (function (BABYLON) {
  9509. /**
  9510. * Helper class to push actions to a pool of workers.
  9511. */
  9512. var WorkerPool = /** @class */ (function () {
  9513. /**
  9514. * Constructor
  9515. * @param workers Array of workers to use for actions
  9516. */
  9517. function WorkerPool(workers) {
  9518. this._pendingActions = new Array();
  9519. this._workerInfos = workers.map(function (worker) { return ({
  9520. worker: worker,
  9521. active: false
  9522. }); });
  9523. }
  9524. /**
  9525. * Terminates all workers and clears any pending actions.
  9526. */
  9527. WorkerPool.prototype.dispose = function () {
  9528. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9529. var workerInfo = _a[_i];
  9530. workerInfo.worker.terminate();
  9531. }
  9532. delete this._workerInfos;
  9533. delete this._pendingActions;
  9534. };
  9535. /**
  9536. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9537. * pended until a worker has completed its action.
  9538. * @param action The action to perform. Call onComplete when the action is complete.
  9539. */
  9540. WorkerPool.prototype.push = function (action) {
  9541. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9542. var workerInfo = _a[_i];
  9543. if (!workerInfo.active) {
  9544. this._execute(workerInfo, action);
  9545. return;
  9546. }
  9547. }
  9548. this._pendingActions.push(action);
  9549. };
  9550. WorkerPool.prototype._execute = function (workerInfo, action) {
  9551. var _this = this;
  9552. workerInfo.active = true;
  9553. action(workerInfo.worker, function () {
  9554. workerInfo.active = false;
  9555. var nextAction = _this._pendingActions.shift();
  9556. if (nextAction) {
  9557. _this._execute(workerInfo, nextAction);
  9558. }
  9559. });
  9560. };
  9561. return WorkerPool;
  9562. }());
  9563. BABYLON.WorkerPool = WorkerPool;
  9564. })(BABYLON || (BABYLON = {}));
  9565. //# sourceMappingURL=babylon.workerPool.js.map
  9566. var BABYLON;
  9567. (function (BABYLON) {
  9568. var _AlphaState = /** @class */ (function () {
  9569. /**
  9570. * Initializes the state.
  9571. */
  9572. function _AlphaState() {
  9573. this._isAlphaBlendDirty = false;
  9574. this._isBlendFunctionParametersDirty = false;
  9575. this._isBlendEquationParametersDirty = false;
  9576. this._isBlendConstantsDirty = false;
  9577. this._alphaBlend = false;
  9578. this._blendFunctionParameters = new Array(4);
  9579. this._blendEquationParameters = new Array(2);
  9580. this._blendConstants = new Array(4);
  9581. this.reset();
  9582. }
  9583. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9584. get: function () {
  9585. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9591. get: function () {
  9592. return this._alphaBlend;
  9593. },
  9594. set: function (value) {
  9595. if (this._alphaBlend === value) {
  9596. return;
  9597. }
  9598. this._alphaBlend = value;
  9599. this._isAlphaBlendDirty = true;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9605. if (this._blendConstants[0] === r &&
  9606. this._blendConstants[1] === g &&
  9607. this._blendConstants[2] === b &&
  9608. this._blendConstants[3] === a) {
  9609. return;
  9610. }
  9611. this._blendConstants[0] = r;
  9612. this._blendConstants[1] = g;
  9613. this._blendConstants[2] = b;
  9614. this._blendConstants[3] = a;
  9615. this._isBlendConstantsDirty = true;
  9616. };
  9617. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9618. if (this._blendFunctionParameters[0] === value0 &&
  9619. this._blendFunctionParameters[1] === value1 &&
  9620. this._blendFunctionParameters[2] === value2 &&
  9621. this._blendFunctionParameters[3] === value3) {
  9622. return;
  9623. }
  9624. this._blendFunctionParameters[0] = value0;
  9625. this._blendFunctionParameters[1] = value1;
  9626. this._blendFunctionParameters[2] = value2;
  9627. this._blendFunctionParameters[3] = value3;
  9628. this._isBlendFunctionParametersDirty = true;
  9629. };
  9630. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9631. if (this._blendEquationParameters[0] === rgb &&
  9632. this._blendEquationParameters[1] === alpha) {
  9633. return;
  9634. }
  9635. this._blendEquationParameters[0] = rgb;
  9636. this._blendEquationParameters[1] = alpha;
  9637. this._isBlendEquationParametersDirty = true;
  9638. };
  9639. _AlphaState.prototype.reset = function () {
  9640. this._alphaBlend = false;
  9641. this._blendFunctionParameters[0] = null;
  9642. this._blendFunctionParameters[1] = null;
  9643. this._blendFunctionParameters[2] = null;
  9644. this._blendFunctionParameters[3] = null;
  9645. this._blendEquationParameters[0] = null;
  9646. this._blendEquationParameters[1] = null;
  9647. this._blendConstants[0] = null;
  9648. this._blendConstants[1] = null;
  9649. this._blendConstants[2] = null;
  9650. this._blendConstants[3] = null;
  9651. this._isAlphaBlendDirty = true;
  9652. this._isBlendFunctionParametersDirty = false;
  9653. this._isBlendEquationParametersDirty = false;
  9654. this._isBlendConstantsDirty = false;
  9655. };
  9656. _AlphaState.prototype.apply = function (gl) {
  9657. if (!this.isDirty) {
  9658. return;
  9659. }
  9660. // Alpha blend
  9661. if (this._isAlphaBlendDirty) {
  9662. if (this._alphaBlend) {
  9663. gl.enable(gl.BLEND);
  9664. }
  9665. else {
  9666. gl.disable(gl.BLEND);
  9667. }
  9668. this._isAlphaBlendDirty = false;
  9669. }
  9670. // Alpha function
  9671. if (this._isBlendFunctionParametersDirty) {
  9672. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9673. this._isBlendFunctionParametersDirty = false;
  9674. }
  9675. // Alpha equation
  9676. if (this._isBlendEquationParametersDirty) {
  9677. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9678. this._isBlendEquationParametersDirty = false;
  9679. }
  9680. // Constants
  9681. if (this._isBlendConstantsDirty) {
  9682. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9683. this._isBlendConstantsDirty = false;
  9684. }
  9685. };
  9686. return _AlphaState;
  9687. }());
  9688. BABYLON._AlphaState = _AlphaState;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9691. var BABYLON;
  9692. (function (BABYLON) {
  9693. var _DepthCullingState = /** @class */ (function () {
  9694. /**
  9695. * Initializes the state.
  9696. */
  9697. function _DepthCullingState() {
  9698. this._isDepthTestDirty = false;
  9699. this._isDepthMaskDirty = false;
  9700. this._isDepthFuncDirty = false;
  9701. this._isCullFaceDirty = false;
  9702. this._isCullDirty = false;
  9703. this._isZOffsetDirty = false;
  9704. this._isFrontFaceDirty = false;
  9705. this.reset();
  9706. }
  9707. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9708. get: function () {
  9709. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9715. get: function () {
  9716. return this._zOffset;
  9717. },
  9718. set: function (value) {
  9719. if (this._zOffset === value) {
  9720. return;
  9721. }
  9722. this._zOffset = value;
  9723. this._isZOffsetDirty = true;
  9724. },
  9725. enumerable: true,
  9726. configurable: true
  9727. });
  9728. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9729. get: function () {
  9730. return this._cullFace;
  9731. },
  9732. set: function (value) {
  9733. if (this._cullFace === value) {
  9734. return;
  9735. }
  9736. this._cullFace = value;
  9737. this._isCullFaceDirty = true;
  9738. },
  9739. enumerable: true,
  9740. configurable: true
  9741. });
  9742. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9743. get: function () {
  9744. return this._cull;
  9745. },
  9746. set: function (value) {
  9747. if (this._cull === value) {
  9748. return;
  9749. }
  9750. this._cull = value;
  9751. this._isCullDirty = true;
  9752. },
  9753. enumerable: true,
  9754. configurable: true
  9755. });
  9756. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9757. get: function () {
  9758. return this._depthFunc;
  9759. },
  9760. set: function (value) {
  9761. if (this._depthFunc === value) {
  9762. return;
  9763. }
  9764. this._depthFunc = value;
  9765. this._isDepthFuncDirty = true;
  9766. },
  9767. enumerable: true,
  9768. configurable: true
  9769. });
  9770. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9771. get: function () {
  9772. return this._depthMask;
  9773. },
  9774. set: function (value) {
  9775. if (this._depthMask === value) {
  9776. return;
  9777. }
  9778. this._depthMask = value;
  9779. this._isDepthMaskDirty = true;
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9785. get: function () {
  9786. return this._depthTest;
  9787. },
  9788. set: function (value) {
  9789. if (this._depthTest === value) {
  9790. return;
  9791. }
  9792. this._depthTest = value;
  9793. this._isDepthTestDirty = true;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9799. get: function () {
  9800. return this._frontFace;
  9801. },
  9802. set: function (value) {
  9803. if (this._frontFace === value) {
  9804. return;
  9805. }
  9806. this._frontFace = value;
  9807. this._isFrontFaceDirty = true;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. _DepthCullingState.prototype.reset = function () {
  9813. this._depthMask = true;
  9814. this._depthTest = true;
  9815. this._depthFunc = null;
  9816. this._cullFace = null;
  9817. this._cull = null;
  9818. this._zOffset = 0;
  9819. this._frontFace = null;
  9820. this._isDepthTestDirty = true;
  9821. this._isDepthMaskDirty = true;
  9822. this._isDepthFuncDirty = false;
  9823. this._isCullFaceDirty = false;
  9824. this._isCullDirty = false;
  9825. this._isZOffsetDirty = false;
  9826. this._isFrontFaceDirty = false;
  9827. };
  9828. _DepthCullingState.prototype.apply = function (gl) {
  9829. if (!this.isDirty) {
  9830. return;
  9831. }
  9832. // Cull
  9833. if (this._isCullDirty) {
  9834. if (this.cull) {
  9835. gl.enable(gl.CULL_FACE);
  9836. }
  9837. else {
  9838. gl.disable(gl.CULL_FACE);
  9839. }
  9840. this._isCullDirty = false;
  9841. }
  9842. // Cull face
  9843. if (this._isCullFaceDirty) {
  9844. gl.cullFace(this.cullFace);
  9845. this._isCullFaceDirty = false;
  9846. }
  9847. // Depth mask
  9848. if (this._isDepthMaskDirty) {
  9849. gl.depthMask(this.depthMask);
  9850. this._isDepthMaskDirty = false;
  9851. }
  9852. // Depth test
  9853. if (this._isDepthTestDirty) {
  9854. if (this.depthTest) {
  9855. gl.enable(gl.DEPTH_TEST);
  9856. }
  9857. else {
  9858. gl.disable(gl.DEPTH_TEST);
  9859. }
  9860. this._isDepthTestDirty = false;
  9861. }
  9862. // Depth func
  9863. if (this._isDepthFuncDirty) {
  9864. gl.depthFunc(this.depthFunc);
  9865. this._isDepthFuncDirty = false;
  9866. }
  9867. // zOffset
  9868. if (this._isZOffsetDirty) {
  9869. if (this.zOffset) {
  9870. gl.enable(gl.POLYGON_OFFSET_FILL);
  9871. gl.polygonOffset(this.zOffset, 0);
  9872. }
  9873. else {
  9874. gl.disable(gl.POLYGON_OFFSET_FILL);
  9875. }
  9876. this._isZOffsetDirty = false;
  9877. }
  9878. // Front face
  9879. if (this._isFrontFaceDirty) {
  9880. gl.frontFace(this.frontFace);
  9881. this._isFrontFaceDirty = false;
  9882. }
  9883. };
  9884. return _DepthCullingState;
  9885. }());
  9886. BABYLON._DepthCullingState = _DepthCullingState;
  9887. })(BABYLON || (BABYLON = {}));
  9888. //# sourceMappingURL=babylon.depthCullingState.js.map
  9889. var BABYLON;
  9890. (function (BABYLON) {
  9891. var _StencilState = /** @class */ (function () {
  9892. function _StencilState() {
  9893. this._isStencilTestDirty = false;
  9894. this._isStencilMaskDirty = false;
  9895. this._isStencilFuncDirty = false;
  9896. this._isStencilOpDirty = false;
  9897. this.reset();
  9898. }
  9899. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9900. get: function () {
  9901. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9907. get: function () {
  9908. return this._stencilFunc;
  9909. },
  9910. set: function (value) {
  9911. if (this._stencilFunc === value) {
  9912. return;
  9913. }
  9914. this._stencilFunc = value;
  9915. this._isStencilFuncDirty = true;
  9916. },
  9917. enumerable: true,
  9918. configurable: true
  9919. });
  9920. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9921. get: function () {
  9922. return this._stencilFuncRef;
  9923. },
  9924. set: function (value) {
  9925. if (this._stencilFuncRef === value) {
  9926. return;
  9927. }
  9928. this._stencilFuncRef = value;
  9929. this._isStencilFuncDirty = true;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9935. get: function () {
  9936. return this._stencilFuncMask;
  9937. },
  9938. set: function (value) {
  9939. if (this._stencilFuncMask === value) {
  9940. return;
  9941. }
  9942. this._stencilFuncMask = value;
  9943. this._isStencilFuncDirty = true;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9949. get: function () {
  9950. return this._stencilOpStencilFail;
  9951. },
  9952. set: function (value) {
  9953. if (this._stencilOpStencilFail === value) {
  9954. return;
  9955. }
  9956. this._stencilOpStencilFail = value;
  9957. this._isStencilOpDirty = true;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9963. get: function () {
  9964. return this._stencilOpDepthFail;
  9965. },
  9966. set: function (value) {
  9967. if (this._stencilOpDepthFail === value) {
  9968. return;
  9969. }
  9970. this._stencilOpDepthFail = value;
  9971. this._isStencilOpDirty = true;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9977. get: function () {
  9978. return this._stencilOpStencilDepthPass;
  9979. },
  9980. set: function (value) {
  9981. if (this._stencilOpStencilDepthPass === value) {
  9982. return;
  9983. }
  9984. this._stencilOpStencilDepthPass = value;
  9985. this._isStencilOpDirty = true;
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9991. get: function () {
  9992. return this._stencilMask;
  9993. },
  9994. set: function (value) {
  9995. if (this._stencilMask === value) {
  9996. return;
  9997. }
  9998. this._stencilMask = value;
  9999. this._isStencilMaskDirty = true;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10005. get: function () {
  10006. return this._stencilTest;
  10007. },
  10008. set: function (value) {
  10009. if (this._stencilTest === value) {
  10010. return;
  10011. }
  10012. this._stencilTest = value;
  10013. this._isStencilTestDirty = true;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. _StencilState.prototype.reset = function () {
  10019. this._stencilTest = false;
  10020. this._stencilMask = 0xFF;
  10021. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10022. this._stencilFuncRef = 1;
  10023. this._stencilFuncMask = 0xFF;
  10024. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10025. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10026. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10027. this._isStencilTestDirty = true;
  10028. this._isStencilMaskDirty = true;
  10029. this._isStencilFuncDirty = true;
  10030. this._isStencilOpDirty = true;
  10031. };
  10032. _StencilState.prototype.apply = function (gl) {
  10033. if (!this.isDirty) {
  10034. return;
  10035. }
  10036. // Stencil test
  10037. if (this._isStencilTestDirty) {
  10038. if (this.stencilTest) {
  10039. gl.enable(gl.STENCIL_TEST);
  10040. }
  10041. else {
  10042. gl.disable(gl.STENCIL_TEST);
  10043. }
  10044. this._isStencilTestDirty = false;
  10045. }
  10046. // Stencil mask
  10047. if (this._isStencilMaskDirty) {
  10048. gl.stencilMask(this.stencilMask);
  10049. this._isStencilMaskDirty = false;
  10050. }
  10051. // Stencil func
  10052. if (this._isStencilFuncDirty) {
  10053. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10054. this._isStencilFuncDirty = false;
  10055. }
  10056. // Stencil op
  10057. if (this._isStencilOpDirty) {
  10058. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10059. this._isStencilOpDirty = false;
  10060. }
  10061. };
  10062. return _StencilState;
  10063. }());
  10064. BABYLON._StencilState = _StencilState;
  10065. })(BABYLON || (BABYLON = {}));
  10066. //# sourceMappingURL=babylon.stencilState.js.map
  10067. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10068. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10069. s = arguments[i];
  10070. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10071. t[p] = s[p];
  10072. }
  10073. return t;
  10074. };
  10075. var BABYLON;
  10076. (function (BABYLON) {
  10077. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10078. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10079. };
  10080. var compileRawShader = function (gl, source, type) {
  10081. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10082. gl.shaderSource(shader, source);
  10083. gl.compileShader(shader);
  10084. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10085. var log = gl.getShaderInfoLog(shader);
  10086. if (log) {
  10087. throw new Error(log);
  10088. }
  10089. }
  10090. if (!shader) {
  10091. throw new Error("Something went wrong while compile the shader.");
  10092. }
  10093. return shader;
  10094. };
  10095. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10096. var magFilter = gl.NEAREST;
  10097. var minFilter = gl.NEAREST;
  10098. switch (samplingMode) {
  10099. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10100. magFilter = gl.LINEAR;
  10101. if (generateMipMaps) {
  10102. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10103. }
  10104. else {
  10105. minFilter = gl.LINEAR;
  10106. }
  10107. break;
  10108. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10109. magFilter = gl.LINEAR;
  10110. if (generateMipMaps) {
  10111. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10112. }
  10113. else {
  10114. minFilter = gl.LINEAR;
  10115. }
  10116. break;
  10117. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10118. magFilter = gl.NEAREST;
  10119. if (generateMipMaps) {
  10120. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10121. }
  10122. else {
  10123. minFilter = gl.NEAREST;
  10124. }
  10125. break;
  10126. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10127. magFilter = gl.NEAREST;
  10128. if (generateMipMaps) {
  10129. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10130. }
  10131. else {
  10132. minFilter = gl.NEAREST;
  10133. }
  10134. break;
  10135. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10136. magFilter = gl.NEAREST;
  10137. if (generateMipMaps) {
  10138. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10139. }
  10140. else {
  10141. minFilter = gl.LINEAR;
  10142. }
  10143. break;
  10144. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10145. magFilter = gl.NEAREST;
  10146. if (generateMipMaps) {
  10147. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10148. }
  10149. else {
  10150. minFilter = gl.LINEAR;
  10151. }
  10152. break;
  10153. case BABYLON.Texture.NEAREST_LINEAR:
  10154. magFilter = gl.NEAREST;
  10155. minFilter = gl.LINEAR;
  10156. break;
  10157. case BABYLON.Texture.NEAREST_NEAREST:
  10158. magFilter = gl.NEAREST;
  10159. minFilter = gl.NEAREST;
  10160. break;
  10161. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10162. magFilter = gl.LINEAR;
  10163. if (generateMipMaps) {
  10164. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10165. }
  10166. else {
  10167. minFilter = gl.NEAREST;
  10168. }
  10169. break;
  10170. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10171. magFilter = gl.LINEAR;
  10172. if (generateMipMaps) {
  10173. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10174. }
  10175. else {
  10176. minFilter = gl.NEAREST;
  10177. }
  10178. break;
  10179. case BABYLON.Texture.LINEAR_LINEAR:
  10180. magFilter = gl.LINEAR;
  10181. minFilter = gl.LINEAR;
  10182. break;
  10183. case BABYLON.Texture.LINEAR_NEAREST:
  10184. magFilter = gl.LINEAR;
  10185. minFilter = gl.NEAREST;
  10186. break;
  10187. }
  10188. return {
  10189. min: minFilter,
  10190. mag: magFilter
  10191. };
  10192. };
  10193. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10194. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10195. var img;
  10196. var onload = function () {
  10197. loadedImages[index] = img;
  10198. loadedImages._internalCount++;
  10199. if (scene) {
  10200. scene._removePendingData(img);
  10201. }
  10202. if (loadedImages._internalCount === 6) {
  10203. onfinish(loadedImages);
  10204. }
  10205. };
  10206. var onerror = function (message, exception) {
  10207. if (scene) {
  10208. scene._removePendingData(img);
  10209. }
  10210. if (onErrorCallBack) {
  10211. onErrorCallBack(message, exception);
  10212. }
  10213. };
  10214. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10215. if (scene) {
  10216. scene._addPendingData(img);
  10217. }
  10218. };
  10219. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10220. if (onError === void 0) { onError = null; }
  10221. var loadedImages = [];
  10222. loadedImages._internalCount = 0;
  10223. for (var index = 0; index < 6; index++) {
  10224. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10225. }
  10226. };
  10227. var BufferPointer = /** @class */ (function () {
  10228. function BufferPointer() {
  10229. }
  10230. return BufferPointer;
  10231. }());
  10232. var InstancingAttributeInfo = /** @class */ (function () {
  10233. function InstancingAttributeInfo() {
  10234. }
  10235. return InstancingAttributeInfo;
  10236. }());
  10237. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10238. /**
  10239. * Define options used to create a render target texture
  10240. */
  10241. var RenderTargetCreationOptions = /** @class */ (function () {
  10242. function RenderTargetCreationOptions() {
  10243. }
  10244. return RenderTargetCreationOptions;
  10245. }());
  10246. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10247. /**
  10248. * Define options used to create a depth texture
  10249. */
  10250. var DepthTextureCreationOptions = /** @class */ (function () {
  10251. function DepthTextureCreationOptions() {
  10252. }
  10253. return DepthTextureCreationOptions;
  10254. }());
  10255. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10256. /**
  10257. * Regroup several parameters relative to the browser in use
  10258. */
  10259. var EngineCapabilities = /** @class */ (function () {
  10260. function EngineCapabilities() {
  10261. }
  10262. return EngineCapabilities;
  10263. }());
  10264. BABYLON.EngineCapabilities = EngineCapabilities;
  10265. /**
  10266. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10267. */
  10268. var Engine = /** @class */ (function () {
  10269. /**
  10270. * @constructor
  10271. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10272. * @param antialias defines enable antialiasing (default: false)
  10273. * @param options defines further options to be sent to the getContext() function
  10274. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10275. */
  10276. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10277. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10278. var _this = this;
  10279. // Public members
  10280. this.forcePOTTextures = false;
  10281. this.isFullscreen = false;
  10282. this.isPointerLock = false;
  10283. this.cullBackFaces = true;
  10284. this.renderEvenInBackground = true;
  10285. this.preventCacheWipeBetweenFrames = false;
  10286. // To enable/disable IDB support and avoid XHR on .manifest
  10287. this.enableOfflineSupport = false;
  10288. this.scenes = new Array();
  10289. this.postProcesses = new Array();
  10290. // Observables
  10291. /**
  10292. * Observable event triggered each time the rendering canvas is resized
  10293. */
  10294. this.onResizeObservable = new BABYLON.Observable();
  10295. /**
  10296. * Observable event triggered each time the canvas loses focus
  10297. */
  10298. this.onCanvasBlurObservable = new BABYLON.Observable();
  10299. /**
  10300. * Observable event triggered each time the canvas gains focus
  10301. */
  10302. this.onCanvasFocusObservable = new BABYLON.Observable();
  10303. /**
  10304. * Observable event triggered each time the canvas receives pointerout event
  10305. */
  10306. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10307. /**
  10308. * Observable event triggered before each texture is initialized
  10309. */
  10310. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10311. //WebVR
  10312. this._vrDisplay = undefined;
  10313. this._vrSupported = false;
  10314. this._vrExclusivePointerMode = false;
  10315. // Uniform buffers list
  10316. this.disableUniformBuffers = false;
  10317. this._uniformBuffers = new Array();
  10318. // Observables
  10319. /**
  10320. * Observable raised when the engine begins a new frame
  10321. */
  10322. this.onBeginFrameObservable = new BABYLON.Observable();
  10323. /**
  10324. * Observable raised when the engine ends the current frame
  10325. */
  10326. this.onEndFrameObservable = new BABYLON.Observable();
  10327. /**
  10328. * Observable raised when the engine is about to compile a shader
  10329. */
  10330. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10331. /**
  10332. * Observable raised when the engine has jsut compiled a shader
  10333. */
  10334. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10335. this._windowIsBackground = false;
  10336. this._webGLVersion = 1.0;
  10337. this._badOS = false;
  10338. this._badDesktopOS = false;
  10339. /**
  10340. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10341. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10342. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10343. */
  10344. this.disableTextureBindingOptimization = false;
  10345. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10346. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10347. this.onVRRequestPresentStart = new BABYLON.Observable();
  10348. this._colorWrite = true;
  10349. this._drawCalls = new BABYLON.PerfCounter();
  10350. this._textureCollisions = new BABYLON.PerfCounter();
  10351. this._renderingQueueLaunched = false;
  10352. this._activeRenderLoops = new Array();
  10353. // Deterministic lockstepMaxSteps
  10354. this._deterministicLockstep = false;
  10355. this._lockstepMaxSteps = 4;
  10356. // Lost context
  10357. this.onContextLostObservable = new BABYLON.Observable();
  10358. this.onContextRestoredObservable = new BABYLON.Observable();
  10359. this._contextWasLost = false;
  10360. this._doNotHandleContextLost = false;
  10361. // FPS
  10362. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10363. this._fps = 60;
  10364. this._deltaTime = 0;
  10365. /**
  10366. * Turn this value on if you want to pause FPS computation when in background
  10367. */
  10368. this.disablePerformanceMonitorInBackground = false;
  10369. // States
  10370. this._depthCullingState = new BABYLON._DepthCullingState();
  10371. this._stencilState = new BABYLON._StencilState();
  10372. this._alphaState = new BABYLON._AlphaState();
  10373. this._alphaMode = Engine.ALPHA_DISABLE;
  10374. // Cache
  10375. this._internalTexturesCache = new Array();
  10376. this._activeChannel = 0;
  10377. this._currentTextureChannel = -1;
  10378. this._boundTexturesCache = {};
  10379. this._compiledEffects = {};
  10380. this._vertexAttribArraysEnabled = [];
  10381. this._uintIndicesCurrentlySet = false;
  10382. this._currentBoundBuffer = new Array();
  10383. this._currentBufferPointers = new Array();
  10384. this._currentInstanceLocations = new Array();
  10385. this._currentInstanceBuffers = new Array();
  10386. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10387. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10388. this._vaoRecordInProgress = false;
  10389. this._mustWipeVertexAttributes = false;
  10390. this._nextFreeTextureSlots = new Array();
  10391. this._maxSimultaneousTextures = 0;
  10392. this._activeRequests = new Array();
  10393. // Hardware supported Compressed Textures
  10394. this._texturesSupported = new Array();
  10395. this._onVRFullScreenTriggered = function () {
  10396. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10397. //get the old size before we change
  10398. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10399. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10400. //get the width and height, change the render size
  10401. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10402. _this.setHardwareScalingLevel(1);
  10403. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10404. }
  10405. else {
  10406. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10407. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10408. }
  10409. };
  10410. this._boundUniforms = {};
  10411. // Register promises
  10412. BABYLON.PromisePolyfill.Apply();
  10413. var canvas = null;
  10414. Engine.Instances.push(this);
  10415. if (!canvasOrContext) {
  10416. return;
  10417. }
  10418. options = options || {};
  10419. if (canvasOrContext.getContext) {
  10420. canvas = canvasOrContext;
  10421. this._renderingCanvas = canvas;
  10422. if (antialias != null) {
  10423. options.antialias = antialias;
  10424. }
  10425. if (options.deterministicLockstep === undefined) {
  10426. options.deterministicLockstep = false;
  10427. }
  10428. if (options.lockstepMaxSteps === undefined) {
  10429. options.lockstepMaxSteps = 4;
  10430. }
  10431. if (options.preserveDrawingBuffer === undefined) {
  10432. options.preserveDrawingBuffer = false;
  10433. }
  10434. if (options.audioEngine === undefined) {
  10435. options.audioEngine = true;
  10436. }
  10437. if (options.stencil === undefined) {
  10438. options.stencil = true;
  10439. }
  10440. this._deterministicLockstep = options.deterministicLockstep;
  10441. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10442. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10443. // Exceptions
  10444. if (navigator && navigator.userAgent) {
  10445. var ua = navigator.userAgent;
  10446. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10447. var exception = _a[_i];
  10448. var key = exception.key;
  10449. var targets = exception.targets;
  10450. if (ua.indexOf(key) > -1) {
  10451. if (exception.capture && exception.captureConstraint) {
  10452. var capture = exception.capture;
  10453. var constraint = exception.captureConstraint;
  10454. var regex = new RegExp(capture);
  10455. var matches = regex.exec(ua);
  10456. if (matches && matches.length > 0) {
  10457. var capturedValue = parseInt(matches[matches.length - 1]);
  10458. if (capturedValue >= constraint) {
  10459. continue;
  10460. }
  10461. }
  10462. }
  10463. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10464. var target = targets_1[_b];
  10465. switch (target) {
  10466. case "uniformBuffer":
  10467. this.disableUniformBuffers = true;
  10468. break;
  10469. case "textureBindingOptimization":
  10470. this.disableTextureBindingOptimization = true;
  10471. break;
  10472. }
  10473. }
  10474. break;
  10475. }
  10476. }
  10477. }
  10478. // GL
  10479. if (!options.disableWebGL2Support) {
  10480. try {
  10481. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10482. if (this._gl) {
  10483. this._webGLVersion = 2.0;
  10484. }
  10485. }
  10486. catch (e) {
  10487. // Do nothing
  10488. }
  10489. }
  10490. if (!this._gl) {
  10491. if (!canvas) {
  10492. throw new Error("The provided canvas is null or undefined.");
  10493. }
  10494. try {
  10495. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10496. }
  10497. catch (e) {
  10498. throw new Error("WebGL not supported");
  10499. }
  10500. }
  10501. if (!this._gl) {
  10502. throw new Error("WebGL not supported");
  10503. }
  10504. this._onCanvasFocus = function () {
  10505. _this.onCanvasFocusObservable.notifyObservers(_this);
  10506. };
  10507. this._onCanvasBlur = function () {
  10508. _this.onCanvasBlurObservable.notifyObservers(_this);
  10509. };
  10510. canvas.addEventListener("focus", this._onCanvasFocus);
  10511. canvas.addEventListener("blur", this._onCanvasBlur);
  10512. this._onBlur = function () {
  10513. if (_this.disablePerformanceMonitorInBackground) {
  10514. _this._performanceMonitor.disable();
  10515. }
  10516. _this._windowIsBackground = true;
  10517. };
  10518. this._onFocus = function () {
  10519. if (_this.disablePerformanceMonitorInBackground) {
  10520. _this._performanceMonitor.enable();
  10521. }
  10522. _this._windowIsBackground = false;
  10523. };
  10524. this._onCanvasPointerOut = function (ev) {
  10525. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10526. };
  10527. window.addEventListener("blur", this._onBlur);
  10528. window.addEventListener("focus", this._onFocus);
  10529. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10530. // Context lost
  10531. if (!this._doNotHandleContextLost) {
  10532. this._onContextLost = function (evt) {
  10533. evt.preventDefault();
  10534. _this._contextWasLost = true;
  10535. BABYLON.Tools.Warn("WebGL context lost.");
  10536. _this.onContextLostObservable.notifyObservers(_this);
  10537. };
  10538. this._onContextRestored = function (evt) {
  10539. // Adding a timeout to avoid race condition at browser level
  10540. setTimeout(function () {
  10541. // Rebuild gl context
  10542. _this._initGLContext();
  10543. // Rebuild effects
  10544. _this._rebuildEffects();
  10545. // Rebuild textures
  10546. _this._rebuildInternalTextures();
  10547. // Rebuild buffers
  10548. _this._rebuildBuffers();
  10549. // Cache
  10550. _this.wipeCaches(true);
  10551. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10552. _this.onContextRestoredObservable.notifyObservers(_this);
  10553. _this._contextWasLost = false;
  10554. }, 0);
  10555. };
  10556. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10557. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10558. }
  10559. }
  10560. else {
  10561. this._gl = canvasOrContext;
  10562. this._renderingCanvas = this._gl.canvas;
  10563. if (this._gl.renderbufferStorageMultisample) {
  10564. this._webGLVersion = 2.0;
  10565. }
  10566. options.stencil = this._gl.getContextAttributes().stencil;
  10567. }
  10568. // Viewport
  10569. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10570. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10571. this.resize();
  10572. this._isStencilEnable = options.stencil ? true : false;
  10573. this._initGLContext();
  10574. if (canvas) {
  10575. // Fullscreen
  10576. this._onFullscreenChange = function () {
  10577. if (document.fullscreen !== undefined) {
  10578. _this.isFullscreen = document.fullscreen;
  10579. }
  10580. else if (document.mozFullScreen !== undefined) {
  10581. _this.isFullscreen = document.mozFullScreen;
  10582. }
  10583. else if (document.webkitIsFullScreen !== undefined) {
  10584. _this.isFullscreen = document.webkitIsFullScreen;
  10585. }
  10586. else if (document.msIsFullScreen !== undefined) {
  10587. _this.isFullscreen = document.msIsFullScreen;
  10588. }
  10589. // Pointer lock
  10590. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10591. canvas.requestPointerLock = canvas.requestPointerLock ||
  10592. canvas.msRequestPointerLock ||
  10593. canvas.mozRequestPointerLock ||
  10594. canvas.webkitRequestPointerLock;
  10595. if (canvas.requestPointerLock) {
  10596. canvas.requestPointerLock();
  10597. }
  10598. }
  10599. };
  10600. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10601. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10602. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10603. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10604. // Pointer lock
  10605. this._onPointerLockChange = function () {
  10606. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10607. document.webkitPointerLockElement === canvas ||
  10608. document.msPointerLockElement === canvas ||
  10609. document.pointerLockElement === canvas);
  10610. };
  10611. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10612. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10613. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10614. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10615. this._onVRDisplayPointerRestricted = function () {
  10616. if (canvas) {
  10617. canvas.requestPointerLock();
  10618. }
  10619. };
  10620. this._onVRDisplayPointerUnrestricted = function () {
  10621. document.exitPointerLock();
  10622. };
  10623. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10624. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10625. }
  10626. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10627. Engine.audioEngine = new BABYLON.AudioEngine();
  10628. }
  10629. // Prepare buffer pointers
  10630. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10631. this._currentBufferPointers[i] = new BufferPointer();
  10632. }
  10633. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10634. // Load WebVR Devices
  10635. if (options.autoEnableWebVR) {
  10636. this.initWebVR();
  10637. }
  10638. // Detect if we are running on a faulty buggy OS.
  10639. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10640. // Detect if we are running on a faulty buggy desktop OS.
  10641. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10642. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10643. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10644. }
  10645. Object.defineProperty(Engine, "LastCreatedEngine", {
  10646. get: function () {
  10647. if (Engine.Instances.length === 0) {
  10648. return null;
  10649. }
  10650. return Engine.Instances[Engine.Instances.length - 1];
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "LastCreatedScene", {
  10656. get: function () {
  10657. var lastCreatedEngine = Engine.LastCreatedEngine;
  10658. if (!lastCreatedEngine) {
  10659. return null;
  10660. }
  10661. if (lastCreatedEngine.scenes.length === 0) {
  10662. return null;
  10663. }
  10664. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. /**
  10670. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10671. */
  10672. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10673. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10674. var engine = Engine.Instances[engineIndex];
  10675. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10676. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10677. }
  10678. }
  10679. };
  10680. Object.defineProperty(Engine, "NEVER", {
  10681. get: function () {
  10682. return Engine._NEVER;
  10683. },
  10684. enumerable: true,
  10685. configurable: true
  10686. });
  10687. Object.defineProperty(Engine, "ALWAYS", {
  10688. get: function () {
  10689. return Engine._ALWAYS;
  10690. },
  10691. enumerable: true,
  10692. configurable: true
  10693. });
  10694. Object.defineProperty(Engine, "LESS", {
  10695. get: function () {
  10696. return Engine._LESS;
  10697. },
  10698. enumerable: true,
  10699. configurable: true
  10700. });
  10701. Object.defineProperty(Engine, "EQUAL", {
  10702. get: function () {
  10703. return Engine._EQUAL;
  10704. },
  10705. enumerable: true,
  10706. configurable: true
  10707. });
  10708. Object.defineProperty(Engine, "LEQUAL", {
  10709. get: function () {
  10710. return Engine._LEQUAL;
  10711. },
  10712. enumerable: true,
  10713. configurable: true
  10714. });
  10715. Object.defineProperty(Engine, "GREATER", {
  10716. get: function () {
  10717. return Engine._GREATER;
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(Engine, "GEQUAL", {
  10723. get: function () {
  10724. return Engine._GEQUAL;
  10725. },
  10726. enumerable: true,
  10727. configurable: true
  10728. });
  10729. Object.defineProperty(Engine, "NOTEQUAL", {
  10730. get: function () {
  10731. return Engine._NOTEQUAL;
  10732. },
  10733. enumerable: true,
  10734. configurable: true
  10735. });
  10736. Object.defineProperty(Engine, "KEEP", {
  10737. get: function () {
  10738. return Engine._KEEP;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Engine, "REPLACE", {
  10744. get: function () {
  10745. return Engine._REPLACE;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Engine, "INCR", {
  10751. get: function () {
  10752. return Engine._INCR;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Engine, "DECR", {
  10758. get: function () {
  10759. return Engine._DECR;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Engine, "INVERT", {
  10765. get: function () {
  10766. return Engine._INVERT;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(Engine, "INCR_WRAP", {
  10772. get: function () {
  10773. return Engine._INCR_WRAP;
  10774. },
  10775. enumerable: true,
  10776. configurable: true
  10777. });
  10778. Object.defineProperty(Engine, "DECR_WRAP", {
  10779. get: function () {
  10780. return Engine._DECR_WRAP;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10786. get: function () {
  10787. return Engine._ALPHA_DISABLE;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10793. get: function () {
  10794. return Engine._ALPHA_ONEONE;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine, "ALPHA_ADD", {
  10800. get: function () {
  10801. return Engine._ALPHA_ADD;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10807. get: function () {
  10808. return Engine._ALPHA_COMBINE;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10814. get: function () {
  10815. return Engine._ALPHA_SUBTRACT;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10821. get: function () {
  10822. return Engine._ALPHA_MULTIPLY;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10828. get: function () {
  10829. return Engine._ALPHA_MAXIMIZED;
  10830. },
  10831. enumerable: true,
  10832. configurable: true
  10833. });
  10834. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10835. get: function () {
  10836. return Engine._ALPHA_PREMULTIPLIED;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10842. get: function () {
  10843. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10849. get: function () {
  10850. return Engine._ALPHA_INTERPOLATE;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10856. get: function () {
  10857. return Engine._ALPHA_SCREENMODE;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10863. get: function () {
  10864. return Engine._DELAYLOADSTATE_NONE;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10870. get: function () {
  10871. return Engine._DELAYLOADSTATE_LOADED;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10877. get: function () {
  10878. return Engine._DELAYLOADSTATE_LOADING;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10884. get: function () {
  10885. return Engine._DELAYLOADSTATE_NOTLOADED;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10891. get: function () {
  10892. return Engine._TEXTUREFORMAT_ALPHA;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10898. get: function () {
  10899. return Engine._TEXTUREFORMAT_LUMINANCE;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10905. /**
  10906. * R32F
  10907. */
  10908. get: function () {
  10909. return Engine._TEXTUREFORMAT_R32F;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10915. /**
  10916. * RG32F
  10917. */
  10918. get: function () {
  10919. return Engine._TEXTUREFORMAT_RG32F;
  10920. },
  10921. enumerable: true,
  10922. configurable: true
  10923. });
  10924. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10925. /**
  10926. * RGB32F
  10927. */
  10928. get: function () {
  10929. return Engine._TEXTUREFORMAT_RGB32F;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10935. /**
  10936. * RGBA32F
  10937. */
  10938. get: function () {
  10939. return Engine._TEXTUREFORMAT_RGBA32F;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10945. get: function () {
  10946. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10952. get: function () {
  10953. return Engine._TEXTUREFORMAT_RGB;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10959. get: function () {
  10960. return Engine._TEXTUREFORMAT_RGBA;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10966. get: function () {
  10967. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10973. get: function () {
  10974. return Engine._TEXTURETYPE_FLOAT;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10980. get: function () {
  10981. return Engine._TEXTURETYPE_HALF_FLOAT;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10987. get: function () {
  10988. return Engine._SCALEMODE_FLOOR;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10994. get: function () {
  10995. return Engine._SCALEMODE_NEAREST;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11001. get: function () {
  11002. return Engine._SCALEMODE_CEILING;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(Engine, "Version", {
  11008. get: function () {
  11009. return "3.2.0-alphaB";
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11015. get: function () {
  11016. return this._vrExclusivePointerMode;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11022. get: function () {
  11023. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11024. },
  11025. enumerable: true,
  11026. configurable: true
  11027. });
  11028. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11029. get: function () {
  11030. return this._webGLVersion < 2 || this.forcePOTTextures;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Engine.prototype, "badOS", {
  11036. get: function () {
  11037. return this._badOS;
  11038. },
  11039. enumerable: true,
  11040. configurable: true
  11041. });
  11042. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11043. get: function () {
  11044. return this._badDesktopOS;
  11045. },
  11046. enumerable: true,
  11047. configurable: true
  11048. });
  11049. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11050. get: function () {
  11051. return this._performanceMonitor;
  11052. },
  11053. enumerable: true,
  11054. configurable: true
  11055. });
  11056. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11057. get: function () {
  11058. return this._texturesSupported;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11064. get: function () {
  11065. return this._textureFormatInUse;
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. Object.defineProperty(Engine.prototype, "currentViewport", {
  11071. get: function () {
  11072. return this._cachedViewport;
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11078. // Empty texture
  11079. get: function () {
  11080. if (!this._emptyTexture) {
  11081. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11082. }
  11083. return this._emptyTexture;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11089. get: function () {
  11090. if (!this._emptyTexture3D) {
  11091. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11092. }
  11093. return this._emptyTexture3D;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11099. get: function () {
  11100. if (!this._emptyCubeTexture) {
  11101. var faceData = new Uint8Array(4);
  11102. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11103. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11104. }
  11105. return this._emptyCubeTexture;
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Engine.prototype._rebuildInternalTextures = function () {
  11111. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11112. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11113. var internalTexture = currentState_1[_i];
  11114. internalTexture._rebuild();
  11115. }
  11116. };
  11117. Engine.prototype._rebuildEffects = function () {
  11118. for (var key in this._compiledEffects) {
  11119. var effect = this._compiledEffects[key];
  11120. effect._prepareEffect();
  11121. }
  11122. BABYLON.Effect.ResetCache();
  11123. };
  11124. Engine.prototype._rebuildBuffers = function () {
  11125. // Index / Vertex
  11126. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11127. var scene = _a[_i];
  11128. scene.resetCachedMaterial();
  11129. scene._rebuildGeometries();
  11130. scene._rebuildTextures();
  11131. }
  11132. // Uniforms
  11133. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11134. var uniformBuffer = _c[_b];
  11135. uniformBuffer._rebuild();
  11136. }
  11137. };
  11138. Engine.prototype._initGLContext = function () {
  11139. // Caps
  11140. this._caps = new EngineCapabilities();
  11141. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11142. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11143. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11144. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11145. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11146. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11147. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11148. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11149. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11150. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11151. // Infos
  11152. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11153. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11154. if (rendererInfo != null) {
  11155. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11156. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11157. }
  11158. if (!this._glVendor) {
  11159. this._glVendor = "Unknown vendor";
  11160. }
  11161. if (!this._glRenderer) {
  11162. this._glRenderer = "Unknown renderer";
  11163. }
  11164. // Constants
  11165. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11166. if (this._gl.RGBA16F !== 0x881A) {
  11167. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11168. }
  11169. if (this._gl.RGBA32F !== 0x8814) {
  11170. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11171. }
  11172. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11173. this._gl.DEPTH24_STENCIL8 = 35056;
  11174. }
  11175. // Extensions
  11176. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11177. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11178. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11179. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11180. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11181. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11182. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11183. 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');
  11184. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11185. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11186. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11187. this._caps.highPrecisionShaderSupported = true;
  11188. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11189. if (this._caps.timerQuery) {
  11190. if (this._webGLVersion === 1) {
  11191. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11192. }
  11193. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11194. }
  11195. // Checks if some of the format renders first to allow the use of webgl inspector.
  11196. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11197. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11198. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11199. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11200. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11201. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11202. if (this._webGLVersion > 1) {
  11203. this._gl.HALF_FLOAT_OES = 0x140B;
  11204. }
  11205. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11206. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11207. // Draw buffers
  11208. if (this._webGLVersion > 1) {
  11209. this._caps.drawBuffersExtension = true;
  11210. }
  11211. else {
  11212. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11213. if (drawBuffersExtension !== null) {
  11214. this._caps.drawBuffersExtension = true;
  11215. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11216. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11217. for (var i = 0; i < 16; i++) {
  11218. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11219. }
  11220. }
  11221. else {
  11222. this._caps.drawBuffersExtension = false;
  11223. }
  11224. }
  11225. // Depth Texture
  11226. if (this._webGLVersion > 1) {
  11227. this._caps.depthTextureExtension = true;
  11228. }
  11229. else {
  11230. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11231. if (depthTextureExtension != null) {
  11232. this._caps.depthTextureExtension = true;
  11233. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11234. }
  11235. }
  11236. // Vertex array object
  11237. if (this._webGLVersion > 1) {
  11238. this._caps.vertexArrayObject = true;
  11239. }
  11240. else {
  11241. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11242. if (vertexArrayObjectExtension != null) {
  11243. this._caps.vertexArrayObject = true;
  11244. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11245. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11246. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11247. }
  11248. else {
  11249. this._caps.vertexArrayObject = false;
  11250. }
  11251. }
  11252. // Instances count
  11253. if (this._webGLVersion > 1) {
  11254. this._caps.instancedArrays = true;
  11255. }
  11256. else {
  11257. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11258. if (instanceExtension != null) {
  11259. this._caps.instancedArrays = true;
  11260. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11261. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11262. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11263. }
  11264. else {
  11265. this._caps.instancedArrays = false;
  11266. }
  11267. }
  11268. // Intelligently add supported compressed formats in order to check for.
  11269. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11270. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11271. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11272. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11273. if (this._caps.astc)
  11274. this.texturesSupported.push('-astc.ktx');
  11275. if (this._caps.s3tc)
  11276. this.texturesSupported.push('-dxt.ktx');
  11277. if (this._caps.pvrtc)
  11278. this.texturesSupported.push('-pvrtc.ktx');
  11279. if (this._caps.etc2)
  11280. this.texturesSupported.push('-etc2.ktx');
  11281. if (this._caps.etc1)
  11282. this.texturesSupported.push('-etc1.ktx');
  11283. if (this._gl.getShaderPrecisionFormat) {
  11284. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11285. if (highp) {
  11286. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11287. }
  11288. }
  11289. // Depth buffer
  11290. this.setDepthBuffer(true);
  11291. this.setDepthFunctionToLessOrEqual();
  11292. this.setDepthWrite(true);
  11293. // Texture maps
  11294. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11295. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11296. this._nextFreeTextureSlots.push(slot);
  11297. }
  11298. };
  11299. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11300. get: function () {
  11301. return this._webGLVersion;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11307. /**
  11308. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11309. */
  11310. get: function () {
  11311. return this._isStencilEnable;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Engine.prototype._prepareWorkingCanvas = function () {
  11317. if (this._workingCanvas) {
  11318. return;
  11319. }
  11320. this._workingCanvas = document.createElement("canvas");
  11321. var context = this._workingCanvas.getContext("2d");
  11322. if (context) {
  11323. this._workingContext = context;
  11324. }
  11325. };
  11326. Engine.prototype.resetTextureCache = function () {
  11327. for (var key in this._boundTexturesCache) {
  11328. var boundTexture = this._boundTexturesCache[key];
  11329. if (boundTexture) {
  11330. this._removeDesignatedSlot(boundTexture);
  11331. }
  11332. this._boundTexturesCache[key] = null;
  11333. }
  11334. if (!this.disableTextureBindingOptimization) {
  11335. this._nextFreeTextureSlots = [];
  11336. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11337. this._nextFreeTextureSlots.push(slot);
  11338. }
  11339. }
  11340. this._currentTextureChannel = -1;
  11341. };
  11342. Engine.prototype.isDeterministicLockStep = function () {
  11343. return this._deterministicLockstep;
  11344. };
  11345. Engine.prototype.getLockstepMaxSteps = function () {
  11346. return this._lockstepMaxSteps;
  11347. };
  11348. Engine.prototype.getGlInfo = function () {
  11349. return {
  11350. vendor: this._glVendor,
  11351. renderer: this._glRenderer,
  11352. version: this._glVersion
  11353. };
  11354. };
  11355. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11356. if (useScreen === void 0) { useScreen = false; }
  11357. var viewport = camera.viewport;
  11358. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11359. };
  11360. Engine.prototype.getRenderWidth = function (useScreen) {
  11361. if (useScreen === void 0) { useScreen = false; }
  11362. if (!useScreen && this._currentRenderTarget) {
  11363. return this._currentRenderTarget.width;
  11364. }
  11365. return this._gl.drawingBufferWidth;
  11366. };
  11367. Engine.prototype.getRenderHeight = function (useScreen) {
  11368. if (useScreen === void 0) { useScreen = false; }
  11369. if (!useScreen && this._currentRenderTarget) {
  11370. return this._currentRenderTarget.height;
  11371. }
  11372. return this._gl.drawingBufferHeight;
  11373. };
  11374. Engine.prototype.getRenderingCanvas = function () {
  11375. return this._renderingCanvas;
  11376. };
  11377. Engine.prototype.getRenderingCanvasClientRect = function () {
  11378. if (!this._renderingCanvas) {
  11379. return null;
  11380. }
  11381. return this._renderingCanvas.getBoundingClientRect();
  11382. };
  11383. Engine.prototype.setHardwareScalingLevel = function (level) {
  11384. this._hardwareScalingLevel = level;
  11385. this.resize();
  11386. };
  11387. Engine.prototype.getHardwareScalingLevel = function () {
  11388. return this._hardwareScalingLevel;
  11389. };
  11390. Engine.prototype.getLoadedTexturesCache = function () {
  11391. return this._internalTexturesCache;
  11392. };
  11393. Engine.prototype.getCaps = function () {
  11394. return this._caps;
  11395. };
  11396. Object.defineProperty(Engine.prototype, "drawCalls", {
  11397. /** The number of draw calls submitted last frame */
  11398. get: function () {
  11399. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11400. return 0;
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11406. get: function () {
  11407. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11408. return null;
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Engine.prototype.getDepthFunction = function () {
  11414. return this._depthCullingState.depthFunc;
  11415. };
  11416. Engine.prototype.setDepthFunction = function (depthFunc) {
  11417. this._depthCullingState.depthFunc = depthFunc;
  11418. };
  11419. Engine.prototype.setDepthFunctionToGreater = function () {
  11420. this._depthCullingState.depthFunc = this._gl.GREATER;
  11421. };
  11422. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11423. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11424. };
  11425. Engine.prototype.setDepthFunctionToLess = function () {
  11426. this._depthCullingState.depthFunc = this._gl.LESS;
  11427. };
  11428. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11429. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11430. };
  11431. Engine.prototype.getStencilBuffer = function () {
  11432. return this._stencilState.stencilTest;
  11433. };
  11434. Engine.prototype.setStencilBuffer = function (enable) {
  11435. this._stencilState.stencilTest = enable;
  11436. };
  11437. Engine.prototype.getStencilMask = function () {
  11438. return this._stencilState.stencilMask;
  11439. };
  11440. Engine.prototype.setStencilMask = function (mask) {
  11441. this._stencilState.stencilMask = mask;
  11442. };
  11443. Engine.prototype.getStencilFunction = function () {
  11444. return this._stencilState.stencilFunc;
  11445. };
  11446. Engine.prototype.getStencilFunctionReference = function () {
  11447. return this._stencilState.stencilFuncRef;
  11448. };
  11449. Engine.prototype.getStencilFunctionMask = function () {
  11450. return this._stencilState.stencilFuncMask;
  11451. };
  11452. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11453. this._stencilState.stencilFunc = stencilFunc;
  11454. };
  11455. Engine.prototype.setStencilFunctionReference = function (reference) {
  11456. this._stencilState.stencilFuncRef = reference;
  11457. };
  11458. Engine.prototype.setStencilFunctionMask = function (mask) {
  11459. this._stencilState.stencilFuncMask = mask;
  11460. };
  11461. Engine.prototype.getStencilOperationFail = function () {
  11462. return this._stencilState.stencilOpStencilFail;
  11463. };
  11464. Engine.prototype.getStencilOperationDepthFail = function () {
  11465. return this._stencilState.stencilOpDepthFail;
  11466. };
  11467. Engine.prototype.getStencilOperationPass = function () {
  11468. return this._stencilState.stencilOpStencilDepthPass;
  11469. };
  11470. Engine.prototype.setStencilOperationFail = function (operation) {
  11471. this._stencilState.stencilOpStencilFail = operation;
  11472. };
  11473. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11474. this._stencilState.stencilOpDepthFail = operation;
  11475. };
  11476. Engine.prototype.setStencilOperationPass = function (operation) {
  11477. this._stencilState.stencilOpStencilDepthPass = operation;
  11478. };
  11479. Engine.prototype.setDitheringState = function (value) {
  11480. if (value) {
  11481. this._gl.enable(this._gl.DITHER);
  11482. }
  11483. else {
  11484. this._gl.disable(this._gl.DITHER);
  11485. }
  11486. };
  11487. Engine.prototype.setRasterizerState = function (value) {
  11488. if (value) {
  11489. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11490. }
  11491. else {
  11492. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11493. }
  11494. };
  11495. /**
  11496. * stop executing a render loop function and remove it from the execution array
  11497. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11498. */
  11499. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11500. if (!renderFunction) {
  11501. this._activeRenderLoops = [];
  11502. return;
  11503. }
  11504. var index = this._activeRenderLoops.indexOf(renderFunction);
  11505. if (index >= 0) {
  11506. this._activeRenderLoops.splice(index, 1);
  11507. }
  11508. };
  11509. Engine.prototype._renderLoop = function () {
  11510. if (!this._contextWasLost) {
  11511. var shouldRender = true;
  11512. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11513. shouldRender = false;
  11514. }
  11515. if (shouldRender) {
  11516. // Start new frame
  11517. this.beginFrame();
  11518. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11519. var renderFunction = this._activeRenderLoops[index];
  11520. renderFunction();
  11521. }
  11522. // Present
  11523. this.endFrame();
  11524. }
  11525. }
  11526. if (this._activeRenderLoops.length > 0) {
  11527. // Register new frame
  11528. var requester = null;
  11529. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11530. requester = this._vrDisplay;
  11531. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11532. }
  11533. else {
  11534. this._renderingQueueLaunched = false;
  11535. }
  11536. };
  11537. /**
  11538. * Register and execute a render loop. The engine can have more than one render function.
  11539. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11540. * @example
  11541. * engine.runRenderLoop(function () {
  11542. * scene.render()
  11543. * })
  11544. */
  11545. Engine.prototype.runRenderLoop = function (renderFunction) {
  11546. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11547. return;
  11548. }
  11549. this._activeRenderLoops.push(renderFunction);
  11550. if (!this._renderingQueueLaunched) {
  11551. this._renderingQueueLaunched = true;
  11552. this._bindedRenderFunction = this._renderLoop.bind(this);
  11553. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11554. }
  11555. };
  11556. /**
  11557. * Toggle full screen mode.
  11558. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11559. * @param {any} options - an options object to be sent to the requestFullscreen function
  11560. */
  11561. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11562. if (this.isFullscreen) {
  11563. BABYLON.Tools.ExitFullscreen();
  11564. }
  11565. else {
  11566. this._pointerLockRequested = requestPointerLock;
  11567. if (this._renderingCanvas) {
  11568. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11569. }
  11570. }
  11571. };
  11572. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11573. if (stencil === void 0) { stencil = false; }
  11574. this.applyStates();
  11575. var mode = 0;
  11576. if (backBuffer && color) {
  11577. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11578. mode |= this._gl.COLOR_BUFFER_BIT;
  11579. }
  11580. if (depth) {
  11581. this._gl.clearDepth(1.0);
  11582. mode |= this._gl.DEPTH_BUFFER_BIT;
  11583. }
  11584. if (stencil) {
  11585. this._gl.clearStencil(0);
  11586. mode |= this._gl.STENCIL_BUFFER_BIT;
  11587. }
  11588. this._gl.clear(mode);
  11589. };
  11590. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11591. var gl = this._gl;
  11592. // Save state
  11593. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11594. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11595. // Change state
  11596. gl.enable(gl.SCISSOR_TEST);
  11597. gl.scissor(x, y, width, height);
  11598. // Clear
  11599. this.clear(clearColor, true, true, true);
  11600. // Restore state
  11601. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11602. if (curScissor === true) {
  11603. gl.enable(gl.SCISSOR_TEST);
  11604. }
  11605. else {
  11606. gl.disable(gl.SCISSOR_TEST);
  11607. }
  11608. };
  11609. /**
  11610. * Set the WebGL's viewport
  11611. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11612. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11613. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11614. */
  11615. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11616. var width = requiredWidth || this.getRenderWidth();
  11617. var height = requiredHeight || this.getRenderHeight();
  11618. var x = viewport.x || 0;
  11619. var y = viewport.y || 0;
  11620. this._cachedViewport = viewport;
  11621. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11622. };
  11623. /**
  11624. * Directly set the WebGL Viewport
  11625. * The x, y, width & height are directly passed to the WebGL call
  11626. * @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.
  11627. */
  11628. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11629. var currentViewport = this._cachedViewport;
  11630. this._cachedViewport = null;
  11631. this._gl.viewport(x, y, width, height);
  11632. return currentViewport;
  11633. };
  11634. Engine.prototype.beginFrame = function () {
  11635. this.onBeginFrameObservable.notifyObservers(this);
  11636. this._measureFps();
  11637. };
  11638. Engine.prototype.endFrame = function () {
  11639. //force a flush in case we are using a bad OS.
  11640. if (this._badOS) {
  11641. this.flushFramebuffer();
  11642. }
  11643. //submit frame to the vr device, if enabled
  11644. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11645. // TODO: We should only submit the frame if we read frameData successfully.
  11646. this._vrDisplay.submitFrame();
  11647. }
  11648. this.onEndFrameObservable.notifyObservers(this);
  11649. };
  11650. /**
  11651. * resize the view according to the canvas' size.
  11652. * @example
  11653. * window.addEventListener("resize", function () {
  11654. * engine.resize();
  11655. * });
  11656. */
  11657. Engine.prototype.resize = function () {
  11658. // We're not resizing the size of the canvas while in VR mode & presenting
  11659. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11660. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11661. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11662. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11663. }
  11664. };
  11665. /**
  11666. * force a specific size of the canvas
  11667. * @param {number} width - the new canvas' width
  11668. * @param {number} height - the new canvas' height
  11669. */
  11670. Engine.prototype.setSize = function (width, height) {
  11671. if (!this._renderingCanvas) {
  11672. return;
  11673. }
  11674. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11675. return;
  11676. }
  11677. this._renderingCanvas.width = width;
  11678. this._renderingCanvas.height = height;
  11679. for (var index = 0; index < this.scenes.length; index++) {
  11680. var scene = this.scenes[index];
  11681. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11682. var cam = scene.cameras[camIndex];
  11683. cam._currentRenderId = 0;
  11684. }
  11685. }
  11686. if (this.onResizeObservable.hasObservers) {
  11687. this.onResizeObservable.notifyObservers(this);
  11688. }
  11689. };
  11690. // WebVR functions
  11691. Engine.prototype.isVRDevicePresent = function () {
  11692. return !!this._vrDisplay;
  11693. };
  11694. Engine.prototype.getVRDevice = function () {
  11695. return this._vrDisplay;
  11696. };
  11697. /**
  11698. * Initializes a webVR display and starts listening to display change events.
  11699. * The onVRDisplayChangedObservable will be notified upon these changes.
  11700. * @returns The onVRDisplayChangedObservable.
  11701. */
  11702. Engine.prototype.initWebVR = function () {
  11703. this.initWebVRAsync();
  11704. return this.onVRDisplayChangedObservable;
  11705. };
  11706. /**
  11707. * Initializes a webVR display and starts listening to display change events.
  11708. * The onVRDisplayChangedObservable will be notified upon these changes.
  11709. * @returns A promise containing a VRDisplay and if vr is supported.
  11710. */
  11711. Engine.prototype.initWebVRAsync = function () {
  11712. var _this = this;
  11713. var notifyObservers = function () {
  11714. var eventArgs = {
  11715. vrDisplay: _this._vrDisplay,
  11716. vrSupported: _this._vrSupported
  11717. };
  11718. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11719. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11720. };
  11721. if (!this._onVrDisplayConnect) {
  11722. this._onVrDisplayConnect = function (event) {
  11723. _this._vrDisplay = event.display;
  11724. notifyObservers();
  11725. };
  11726. this._onVrDisplayDisconnect = function () {
  11727. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11728. _this._vrDisplay = undefined;
  11729. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11730. notifyObservers();
  11731. };
  11732. this._onVrDisplayPresentChange = function () {
  11733. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11734. };
  11735. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11736. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11737. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11738. }
  11739. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11740. this._webVRInitPromise.then(notifyObservers);
  11741. return this._webVRInitPromise;
  11742. };
  11743. Engine.prototype.enableVR = function () {
  11744. var _this = this;
  11745. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11746. var onResolved = function () {
  11747. _this.onVRRequestPresentComplete.notifyObservers(true);
  11748. _this._onVRFullScreenTriggered();
  11749. };
  11750. var onRejected = function () {
  11751. _this.onVRRequestPresentComplete.notifyObservers(false);
  11752. };
  11753. this.onVRRequestPresentStart.notifyObservers(this);
  11754. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11755. }
  11756. };
  11757. Engine.prototype.disableVR = function () {
  11758. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11759. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11760. }
  11761. };
  11762. Engine.prototype._getVRDisplaysAsync = function () {
  11763. var _this = this;
  11764. return new Promise(function (res, rej) {
  11765. if (navigator.getVRDisplays) {
  11766. navigator.getVRDisplays().then(function (devices) {
  11767. _this._vrSupported = true;
  11768. // note that devices may actually be an empty array. This is fine;
  11769. // we expect this._vrDisplay to be undefined in this case.
  11770. _this._vrDisplay = devices[0];
  11771. res({
  11772. vrDisplay: _this._vrDisplay,
  11773. vrSupported: _this._vrSupported
  11774. });
  11775. });
  11776. }
  11777. else {
  11778. _this._vrDisplay = undefined;
  11779. _this._vrSupported = false;
  11780. res({
  11781. vrDisplay: _this._vrDisplay,
  11782. vrSupported: _this._vrSupported
  11783. });
  11784. }
  11785. });
  11786. };
  11787. /**
  11788. * Binds the frame buffer to the specified texture.
  11789. * @param texture The texture to render to or null for the default canvas
  11790. * @param faceIndex The face of the texture to render to in case of cube texture
  11791. * @param requiredWidth The width of the target to render to
  11792. * @param requiredHeight The height of the target to render to
  11793. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11794. * @param depthStencilTexture The depth stencil texture to use to render
  11795. */
  11796. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11797. if (this._currentRenderTarget) {
  11798. this.unBindFramebuffer(this._currentRenderTarget);
  11799. }
  11800. this._currentRenderTarget = texture;
  11801. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11802. var gl = this._gl;
  11803. if (texture.isCube) {
  11804. if (faceIndex === undefined) {
  11805. faceIndex = 0;
  11806. }
  11807. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11808. if (depthStencilTexture) {
  11809. if (depthStencilTexture._generateStencilBuffer) {
  11810. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11811. }
  11812. else {
  11813. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11814. }
  11815. }
  11816. }
  11817. if (this._cachedViewport && !forceFullscreenViewport) {
  11818. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11819. }
  11820. else {
  11821. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11822. }
  11823. this.wipeCaches();
  11824. };
  11825. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11826. if (this._currentFramebuffer !== framebuffer) {
  11827. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11828. this._currentFramebuffer = framebuffer;
  11829. }
  11830. };
  11831. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11832. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11833. this._currentRenderTarget = null;
  11834. // If MSAA, we need to bitblt back to main texture
  11835. var gl = this._gl;
  11836. if (texture._MSAAFramebuffer) {
  11837. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11838. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11839. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11840. }
  11841. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11842. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11843. gl.generateMipmap(gl.TEXTURE_2D);
  11844. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11845. }
  11846. if (onBeforeUnbind) {
  11847. if (texture._MSAAFramebuffer) {
  11848. // Bind the correct framebuffer
  11849. this.bindUnboundFramebuffer(texture._framebuffer);
  11850. }
  11851. onBeforeUnbind();
  11852. }
  11853. this.bindUnboundFramebuffer(null);
  11854. };
  11855. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11856. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11857. this._currentRenderTarget = null;
  11858. // If MSAA, we need to bitblt back to main texture
  11859. var gl = this._gl;
  11860. if (textures[0]._MSAAFramebuffer) {
  11861. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11862. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11863. var attachments = textures[0]._attachments;
  11864. if (!attachments) {
  11865. attachments = new Array(textures.length);
  11866. textures[0]._attachments = attachments;
  11867. }
  11868. for (var i = 0; i < textures.length; i++) {
  11869. var texture = textures[i];
  11870. for (var j = 0; j < attachments.length; j++) {
  11871. attachments[j] = gl.NONE;
  11872. }
  11873. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11874. gl.readBuffer(attachments[i]);
  11875. gl.drawBuffers(attachments);
  11876. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11877. }
  11878. for (var i = 0; i < attachments.length; i++) {
  11879. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11880. }
  11881. gl.drawBuffers(attachments);
  11882. }
  11883. for (var i = 0; i < textures.length; i++) {
  11884. var texture = textures[i];
  11885. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11886. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11887. gl.generateMipmap(gl.TEXTURE_2D);
  11888. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11889. }
  11890. }
  11891. if (onBeforeUnbind) {
  11892. if (textures[0]._MSAAFramebuffer) {
  11893. // Bind the correct framebuffer
  11894. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11895. }
  11896. onBeforeUnbind();
  11897. }
  11898. this.bindUnboundFramebuffer(null);
  11899. };
  11900. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11901. if (texture.generateMipMaps) {
  11902. var gl = this._gl;
  11903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11904. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11905. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11906. }
  11907. };
  11908. Engine.prototype.flushFramebuffer = function () {
  11909. this._gl.flush();
  11910. };
  11911. Engine.prototype.restoreDefaultFramebuffer = function () {
  11912. if (this._currentRenderTarget) {
  11913. this.unBindFramebuffer(this._currentRenderTarget);
  11914. }
  11915. else {
  11916. this.bindUnboundFramebuffer(null);
  11917. }
  11918. if (this._cachedViewport) {
  11919. this.setViewport(this._cachedViewport);
  11920. }
  11921. this.wipeCaches();
  11922. };
  11923. // UBOs
  11924. Engine.prototype.createUniformBuffer = function (elements) {
  11925. var ubo = this._gl.createBuffer();
  11926. if (!ubo) {
  11927. throw new Error("Unable to create uniform buffer");
  11928. }
  11929. this.bindUniformBuffer(ubo);
  11930. if (elements instanceof Float32Array) {
  11931. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11932. }
  11933. else {
  11934. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11935. }
  11936. this.bindUniformBuffer(null);
  11937. ubo.references = 1;
  11938. return ubo;
  11939. };
  11940. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11941. var ubo = this._gl.createBuffer();
  11942. if (!ubo) {
  11943. throw new Error("Unable to create dynamic uniform buffer");
  11944. }
  11945. this.bindUniformBuffer(ubo);
  11946. if (elements instanceof Float32Array) {
  11947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11948. }
  11949. else {
  11950. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11951. }
  11952. this.bindUniformBuffer(null);
  11953. ubo.references = 1;
  11954. return ubo;
  11955. };
  11956. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11957. this.bindUniformBuffer(uniformBuffer);
  11958. if (offset === undefined) {
  11959. offset = 0;
  11960. }
  11961. if (count === undefined) {
  11962. if (elements instanceof Float32Array) {
  11963. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11964. }
  11965. else {
  11966. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11967. }
  11968. }
  11969. else {
  11970. if (elements instanceof Float32Array) {
  11971. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11972. }
  11973. else {
  11974. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11975. }
  11976. }
  11977. this.bindUniformBuffer(null);
  11978. };
  11979. // VBOs
  11980. Engine.prototype._resetVertexBufferBinding = function () {
  11981. this.bindArrayBuffer(null);
  11982. this._cachedVertexBuffers = null;
  11983. };
  11984. Engine.prototype.createVertexBuffer = function (vertices) {
  11985. var vbo = this._gl.createBuffer();
  11986. if (!vbo) {
  11987. throw new Error("Unable to create vertex buffer");
  11988. }
  11989. this.bindArrayBuffer(vbo);
  11990. if (vertices instanceof Float32Array) {
  11991. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11992. }
  11993. else {
  11994. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11995. }
  11996. this._resetVertexBufferBinding();
  11997. vbo.references = 1;
  11998. return vbo;
  11999. };
  12000. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12001. var vbo = this._gl.createBuffer();
  12002. if (!vbo) {
  12003. throw new Error("Unable to create dynamic vertex buffer");
  12004. }
  12005. this.bindArrayBuffer(vbo);
  12006. if (vertices instanceof Float32Array) {
  12007. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12008. }
  12009. else {
  12010. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12011. }
  12012. this._resetVertexBufferBinding();
  12013. vbo.references = 1;
  12014. return vbo;
  12015. };
  12016. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12017. if (offset === void 0) { offset = 0; }
  12018. // Force cache update
  12019. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12020. this.bindIndexBuffer(indexBuffer);
  12021. var arrayBuffer;
  12022. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12023. arrayBuffer = indices;
  12024. }
  12025. else {
  12026. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12027. }
  12028. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12029. this._resetIndexBufferBinding();
  12030. };
  12031. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12032. this.bindArrayBuffer(vertexBuffer);
  12033. if (offset === undefined) {
  12034. offset = 0;
  12035. }
  12036. if (count === undefined) {
  12037. if (vertices instanceof Float32Array) {
  12038. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12039. }
  12040. else {
  12041. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12042. }
  12043. }
  12044. else {
  12045. if (vertices instanceof Float32Array) {
  12046. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12047. }
  12048. else {
  12049. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12050. }
  12051. }
  12052. this._resetVertexBufferBinding();
  12053. };
  12054. Engine.prototype._resetIndexBufferBinding = function () {
  12055. this.bindIndexBuffer(null);
  12056. this._cachedIndexBuffer = null;
  12057. };
  12058. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12059. var vbo = this._gl.createBuffer();
  12060. if (!vbo) {
  12061. throw new Error("Unable to create index buffer");
  12062. }
  12063. this.bindIndexBuffer(vbo);
  12064. // Check for 32 bits indices
  12065. var arrayBuffer;
  12066. var need32Bits = false;
  12067. if (indices instanceof Uint16Array) {
  12068. arrayBuffer = indices;
  12069. }
  12070. else {
  12071. //check 32 bit support
  12072. if (this._caps.uintIndices) {
  12073. if (indices instanceof Uint32Array) {
  12074. arrayBuffer = indices;
  12075. need32Bits = true;
  12076. }
  12077. else {
  12078. //number[] or Int32Array, check if 32 bit is necessary
  12079. for (var index = 0; index < indices.length; index++) {
  12080. if (indices[index] > 65535) {
  12081. need32Bits = true;
  12082. break;
  12083. }
  12084. }
  12085. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12086. }
  12087. }
  12088. else {
  12089. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12090. arrayBuffer = new Uint16Array(indices);
  12091. }
  12092. }
  12093. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12094. this._resetIndexBufferBinding();
  12095. vbo.references = 1;
  12096. vbo.is32Bits = need32Bits;
  12097. return vbo;
  12098. };
  12099. Engine.prototype.bindArrayBuffer = function (buffer) {
  12100. if (!this._vaoRecordInProgress) {
  12101. this._unbindVertexArrayObject();
  12102. }
  12103. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12104. };
  12105. Engine.prototype.bindUniformBuffer = function (buffer) {
  12106. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12107. };
  12108. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12109. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12110. };
  12111. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12112. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12113. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12114. };
  12115. ;
  12116. Engine.prototype.bindIndexBuffer = function (buffer) {
  12117. if (!this._vaoRecordInProgress) {
  12118. this._unbindVertexArrayObject();
  12119. }
  12120. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12121. };
  12122. Engine.prototype.bindBuffer = function (buffer, target) {
  12123. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12124. this._gl.bindBuffer(target, buffer);
  12125. this._currentBoundBuffer[target] = buffer;
  12126. }
  12127. };
  12128. Engine.prototype.updateArrayBuffer = function (data) {
  12129. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12130. };
  12131. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12132. var pointer = this._currentBufferPointers[indx];
  12133. var changed = false;
  12134. if (!pointer.active) {
  12135. changed = true;
  12136. pointer.active = true;
  12137. pointer.index = indx;
  12138. pointer.size = size;
  12139. pointer.type = type;
  12140. pointer.normalized = normalized;
  12141. pointer.stride = stride;
  12142. pointer.offset = offset;
  12143. pointer.buffer = buffer;
  12144. }
  12145. else {
  12146. if (pointer.buffer !== buffer) {
  12147. pointer.buffer = buffer;
  12148. changed = true;
  12149. }
  12150. if (pointer.size !== size) {
  12151. pointer.size = size;
  12152. changed = true;
  12153. }
  12154. if (pointer.type !== type) {
  12155. pointer.type = type;
  12156. changed = true;
  12157. }
  12158. if (pointer.normalized !== normalized) {
  12159. pointer.normalized = normalized;
  12160. changed = true;
  12161. }
  12162. if (pointer.stride !== stride) {
  12163. pointer.stride = stride;
  12164. changed = true;
  12165. }
  12166. if (pointer.offset !== offset) {
  12167. pointer.offset = offset;
  12168. changed = true;
  12169. }
  12170. }
  12171. if (changed || this._vaoRecordInProgress) {
  12172. this.bindArrayBuffer(buffer);
  12173. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12174. }
  12175. };
  12176. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12177. if (indexBuffer == null) {
  12178. return;
  12179. }
  12180. if (this._cachedIndexBuffer !== indexBuffer) {
  12181. this._cachedIndexBuffer = indexBuffer;
  12182. this.bindIndexBuffer(indexBuffer);
  12183. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12184. }
  12185. };
  12186. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12187. var attributes = effect.getAttributesNames();
  12188. if (!this._vaoRecordInProgress) {
  12189. this._unbindVertexArrayObject();
  12190. }
  12191. this.unbindAllAttributes();
  12192. for (var index = 0; index < attributes.length; index++) {
  12193. var order = effect.getAttributeLocation(index);
  12194. if (order >= 0) {
  12195. var vertexBuffer = vertexBuffers[attributes[index]];
  12196. if (!vertexBuffer) {
  12197. continue;
  12198. }
  12199. this._gl.enableVertexAttribArray(order);
  12200. if (!this._vaoRecordInProgress) {
  12201. this._vertexAttribArraysEnabled[order] = true;
  12202. }
  12203. var buffer = vertexBuffer.getBuffer();
  12204. if (buffer) {
  12205. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12206. if (vertexBuffer.getIsInstanced()) {
  12207. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12208. if (!this._vaoRecordInProgress) {
  12209. this._currentInstanceLocations.push(order);
  12210. this._currentInstanceBuffers.push(buffer);
  12211. }
  12212. }
  12213. }
  12214. }
  12215. }
  12216. };
  12217. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12218. var vao = this._gl.createVertexArray();
  12219. this._vaoRecordInProgress = true;
  12220. this._gl.bindVertexArray(vao);
  12221. this._mustWipeVertexAttributes = true;
  12222. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12223. this.bindIndexBuffer(indexBuffer);
  12224. this._vaoRecordInProgress = false;
  12225. this._gl.bindVertexArray(null);
  12226. return vao;
  12227. };
  12228. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12229. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12230. this._cachedVertexArrayObject = vertexArrayObject;
  12231. this._gl.bindVertexArray(vertexArrayObject);
  12232. this._cachedVertexBuffers = null;
  12233. this._cachedIndexBuffer = null;
  12234. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12235. this._mustWipeVertexAttributes = true;
  12236. }
  12237. };
  12238. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12239. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12240. this._cachedVertexBuffers = vertexBuffer;
  12241. this._cachedEffectForVertexBuffers = effect;
  12242. var attributesCount = effect.getAttributesCount();
  12243. this._unbindVertexArrayObject();
  12244. this.unbindAllAttributes();
  12245. var offset = 0;
  12246. for (var index = 0; index < attributesCount; index++) {
  12247. if (index < vertexDeclaration.length) {
  12248. var order = effect.getAttributeLocation(index);
  12249. if (order >= 0) {
  12250. this._gl.enableVertexAttribArray(order);
  12251. this._vertexAttribArraysEnabled[order] = true;
  12252. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12253. }
  12254. offset += vertexDeclaration[index] * 4;
  12255. }
  12256. }
  12257. }
  12258. this._bindIndexBufferWithCache(indexBuffer);
  12259. };
  12260. Engine.prototype._unbindVertexArrayObject = function () {
  12261. if (!this._cachedVertexArrayObject) {
  12262. return;
  12263. }
  12264. this._cachedVertexArrayObject = null;
  12265. this._gl.bindVertexArray(null);
  12266. };
  12267. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12268. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12269. this._cachedVertexBuffers = vertexBuffers;
  12270. this._cachedEffectForVertexBuffers = effect;
  12271. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12272. }
  12273. this._bindIndexBufferWithCache(indexBuffer);
  12274. };
  12275. Engine.prototype.unbindInstanceAttributes = function () {
  12276. var boundBuffer;
  12277. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12278. var instancesBuffer = this._currentInstanceBuffers[i];
  12279. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12280. boundBuffer = instancesBuffer;
  12281. this.bindArrayBuffer(instancesBuffer);
  12282. }
  12283. var offsetLocation = this._currentInstanceLocations[i];
  12284. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12285. }
  12286. this._currentInstanceBuffers.length = 0;
  12287. this._currentInstanceLocations.length = 0;
  12288. };
  12289. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12290. this._gl.deleteVertexArray(vao);
  12291. };
  12292. Engine.prototype._releaseBuffer = function (buffer) {
  12293. buffer.references--;
  12294. if (buffer.references === 0) {
  12295. this._gl.deleteBuffer(buffer);
  12296. return true;
  12297. }
  12298. return false;
  12299. };
  12300. Engine.prototype.createInstancesBuffer = function (capacity) {
  12301. var buffer = this._gl.createBuffer();
  12302. if (!buffer) {
  12303. throw new Error("Unable to create instance buffer");
  12304. }
  12305. buffer.capacity = capacity;
  12306. this.bindArrayBuffer(buffer);
  12307. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12308. return buffer;
  12309. };
  12310. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12311. this._gl.deleteBuffer(buffer);
  12312. };
  12313. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12314. this.bindArrayBuffer(instancesBuffer);
  12315. if (data) {
  12316. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12317. }
  12318. if (offsetLocations[0].index !== undefined) {
  12319. var stride = 0;
  12320. for (var i = 0; i < offsetLocations.length; i++) {
  12321. var ai = offsetLocations[i];
  12322. stride += ai.attributeSize * 4;
  12323. }
  12324. for (var i = 0; i < offsetLocations.length; i++) {
  12325. var ai = offsetLocations[i];
  12326. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12327. this._gl.enableVertexAttribArray(ai.index);
  12328. this._vertexAttribArraysEnabled[ai.index] = true;
  12329. }
  12330. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12331. this._gl.vertexAttribDivisor(ai.index, 1);
  12332. this._currentInstanceLocations.push(ai.index);
  12333. this._currentInstanceBuffers.push(instancesBuffer);
  12334. }
  12335. }
  12336. else {
  12337. for (var index = 0; index < 4; index++) {
  12338. var offsetLocation = offsetLocations[index];
  12339. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12340. this._gl.enableVertexAttribArray(offsetLocation);
  12341. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12342. }
  12343. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12344. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12345. this._currentInstanceLocations.push(offsetLocation);
  12346. this._currentInstanceBuffers.push(instancesBuffer);
  12347. }
  12348. }
  12349. };
  12350. Engine.prototype.applyStates = function () {
  12351. this._depthCullingState.apply(this._gl);
  12352. this._stencilState.apply(this._gl);
  12353. this._alphaState.apply(this._gl);
  12354. };
  12355. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12356. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12357. };
  12358. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12359. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12360. };
  12361. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12362. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12363. };
  12364. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12365. // Apply states
  12366. this.applyStates();
  12367. this._drawCalls.addCount(1, false);
  12368. // Render
  12369. var drawMode = this.DrawMode(fillMode);
  12370. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12371. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12372. if (instancesCount) {
  12373. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12374. }
  12375. else {
  12376. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12377. }
  12378. };
  12379. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12380. // Apply states
  12381. this.applyStates();
  12382. this._drawCalls.addCount(1, false);
  12383. var drawMode = this.DrawMode(fillMode);
  12384. if (instancesCount) {
  12385. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12386. }
  12387. else {
  12388. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12389. }
  12390. };
  12391. Engine.prototype.DrawMode = function (fillMode) {
  12392. switch (fillMode) {
  12393. // Triangle views
  12394. case BABYLON.Material.TriangleFillMode:
  12395. return this._gl.TRIANGLES;
  12396. case BABYLON.Material.PointFillMode:
  12397. return this._gl.POINTS;
  12398. case BABYLON.Material.WireFrameFillMode:
  12399. return this._gl.LINES;
  12400. // Draw modes
  12401. case BABYLON.Material.PointListDrawMode:
  12402. return this._gl.POINTS;
  12403. case BABYLON.Material.LineListDrawMode:
  12404. return this._gl.LINES;
  12405. case BABYLON.Material.LineLoopDrawMode:
  12406. return this._gl.LINE_LOOP;
  12407. case BABYLON.Material.LineStripDrawMode:
  12408. return this._gl.LINE_STRIP;
  12409. case BABYLON.Material.TriangleStripDrawMode:
  12410. return this._gl.TRIANGLE_STRIP;
  12411. case BABYLON.Material.TriangleFanDrawMode:
  12412. return this._gl.TRIANGLE_FAN;
  12413. default:
  12414. return this._gl.TRIANGLES;
  12415. }
  12416. };
  12417. // Shaders
  12418. Engine.prototype._releaseEffect = function (effect) {
  12419. if (this._compiledEffects[effect._key]) {
  12420. delete this._compiledEffects[effect._key];
  12421. this._deleteProgram(effect.getProgram());
  12422. }
  12423. };
  12424. Engine.prototype._deleteProgram = function (program) {
  12425. if (program) {
  12426. program.__SPECTOR_rebuildProgram = null;
  12427. if (program.transformFeedback) {
  12428. this.deleteTransformFeedback(program.transformFeedback);
  12429. program.transformFeedback = null;
  12430. }
  12431. this._gl.deleteProgram(program);
  12432. }
  12433. };
  12434. /**
  12435. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12436. * @param samplers An array of string used to represent textures
  12437. */
  12438. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12439. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12440. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12441. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12442. if (this._compiledEffects[name]) {
  12443. var compiledEffect = this._compiledEffects[name];
  12444. if (onCompiled && compiledEffect.isReady()) {
  12445. onCompiled(compiledEffect);
  12446. }
  12447. return compiledEffect;
  12448. }
  12449. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12450. effect._key = name;
  12451. this._compiledEffects[name] = effect;
  12452. return effect;
  12453. };
  12454. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12455. if (uniformsNames === void 0) { uniformsNames = []; }
  12456. if (samplers === void 0) { samplers = []; }
  12457. if (defines === void 0) { defines = ""; }
  12458. return this.createEffect({
  12459. vertex: "particles",
  12460. fragmentElement: fragmentName
  12461. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12462. };
  12463. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12464. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12465. context = context || this._gl;
  12466. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12467. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12468. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12469. };
  12470. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12471. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12472. context = context || this._gl;
  12473. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12474. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12475. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12476. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12477. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12478. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12479. return program;
  12480. };
  12481. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12482. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12483. var shaderProgram = context.createProgram();
  12484. if (!shaderProgram) {
  12485. throw new Error("Unable to create program");
  12486. }
  12487. context.attachShader(shaderProgram, vertexShader);
  12488. context.attachShader(shaderProgram, fragmentShader);
  12489. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12490. var transformFeedback = this.createTransformFeedback();
  12491. this.bindTransformFeedback(transformFeedback);
  12492. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12493. shaderProgram.transformFeedback = transformFeedback;
  12494. }
  12495. context.linkProgram(shaderProgram);
  12496. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12497. this.bindTransformFeedback(null);
  12498. }
  12499. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12500. if (!linked) {
  12501. context.validateProgram(shaderProgram);
  12502. var error = context.getProgramInfoLog(shaderProgram);
  12503. if (error) {
  12504. throw new Error(error);
  12505. }
  12506. }
  12507. context.deleteShader(vertexShader);
  12508. context.deleteShader(fragmentShader);
  12509. return shaderProgram;
  12510. };
  12511. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12512. var results = new Array();
  12513. for (var index = 0; index < uniformsNames.length; index++) {
  12514. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12515. }
  12516. return results;
  12517. };
  12518. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12519. var results = [];
  12520. for (var index = 0; index < attributesNames.length; index++) {
  12521. try {
  12522. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12523. }
  12524. catch (e) {
  12525. results.push(-1);
  12526. }
  12527. }
  12528. return results;
  12529. };
  12530. Engine.prototype.enableEffect = function (effect) {
  12531. if (!effect) {
  12532. return;
  12533. }
  12534. // Use program
  12535. this.bindSamplers(effect);
  12536. this._currentEffect = effect;
  12537. if (effect.onBind) {
  12538. effect.onBind(effect);
  12539. }
  12540. effect.onBindObservable.notifyObservers(effect);
  12541. };
  12542. Engine.prototype.setIntArray = function (uniform, array) {
  12543. if (!uniform)
  12544. return;
  12545. this._gl.uniform1iv(uniform, array);
  12546. };
  12547. Engine.prototype.setIntArray2 = function (uniform, array) {
  12548. if (!uniform || array.length % 2 !== 0)
  12549. return;
  12550. this._gl.uniform2iv(uniform, array);
  12551. };
  12552. Engine.prototype.setIntArray3 = function (uniform, array) {
  12553. if (!uniform || array.length % 3 !== 0)
  12554. return;
  12555. this._gl.uniform3iv(uniform, array);
  12556. };
  12557. Engine.prototype.setIntArray4 = function (uniform, array) {
  12558. if (!uniform || array.length % 4 !== 0)
  12559. return;
  12560. this._gl.uniform4iv(uniform, array);
  12561. };
  12562. Engine.prototype.setFloatArray = function (uniform, array) {
  12563. if (!uniform)
  12564. return;
  12565. this._gl.uniform1fv(uniform, array);
  12566. };
  12567. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12568. if (!uniform || array.length % 2 !== 0)
  12569. return;
  12570. this._gl.uniform2fv(uniform, array);
  12571. };
  12572. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12573. if (!uniform || array.length % 3 !== 0)
  12574. return;
  12575. this._gl.uniform3fv(uniform, array);
  12576. };
  12577. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12578. if (!uniform || array.length % 4 !== 0)
  12579. return;
  12580. this._gl.uniform4fv(uniform, array);
  12581. };
  12582. Engine.prototype.setArray = function (uniform, array) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniform1fv(uniform, array);
  12586. };
  12587. Engine.prototype.setArray2 = function (uniform, array) {
  12588. if (!uniform || array.length % 2 !== 0)
  12589. return;
  12590. this._gl.uniform2fv(uniform, array);
  12591. };
  12592. Engine.prototype.setArray3 = function (uniform, array) {
  12593. if (!uniform || array.length % 3 !== 0)
  12594. return;
  12595. this._gl.uniform3fv(uniform, array);
  12596. };
  12597. Engine.prototype.setArray4 = function (uniform, array) {
  12598. if (!uniform || array.length % 4 !== 0)
  12599. return;
  12600. this._gl.uniform4fv(uniform, array);
  12601. };
  12602. Engine.prototype.setMatrices = function (uniform, matrices) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12606. };
  12607. Engine.prototype.setMatrix = function (uniform, matrix) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12611. };
  12612. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12616. };
  12617. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12621. };
  12622. Engine.prototype.setInt = function (uniform, value) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform1i(uniform, value);
  12626. };
  12627. Engine.prototype.setFloat = function (uniform, value) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform1f(uniform, value);
  12631. };
  12632. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12633. if (!uniform)
  12634. return;
  12635. this._gl.uniform2f(uniform, x, y);
  12636. };
  12637. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12638. if (!uniform)
  12639. return;
  12640. this._gl.uniform3f(uniform, x, y, z);
  12641. };
  12642. Engine.prototype.setBool = function (uniform, bool) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniform1i(uniform, bool);
  12646. };
  12647. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12648. if (!uniform)
  12649. return;
  12650. this._gl.uniform4f(uniform, x, y, z, w);
  12651. };
  12652. Engine.prototype.setColor3 = function (uniform, color3) {
  12653. if (!uniform)
  12654. return;
  12655. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12656. };
  12657. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12658. if (!uniform)
  12659. return;
  12660. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12661. };
  12662. /**
  12663. * Sets a Color4 on a uniform variable
  12664. * @param uniform defines the uniform location
  12665. * @param color4 defines the value to be set
  12666. */
  12667. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12668. if (!uniform)
  12669. return;
  12670. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12671. };
  12672. // States
  12673. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12674. if (zOffset === void 0) { zOffset = 0; }
  12675. if (reverseSide === void 0) { reverseSide = false; }
  12676. // Culling
  12677. if (this._depthCullingState.cull !== culling || force) {
  12678. this._depthCullingState.cull = culling;
  12679. }
  12680. // Cull face
  12681. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12682. if (this._depthCullingState.cullFace !== cullFace || force) {
  12683. this._depthCullingState.cullFace = cullFace;
  12684. }
  12685. // Z offset
  12686. this.setZOffset(zOffset);
  12687. // Front face
  12688. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12689. if (this._depthCullingState.frontFace !== frontFace || force) {
  12690. this._depthCullingState.frontFace = frontFace;
  12691. }
  12692. };
  12693. Engine.prototype.setZOffset = function (value) {
  12694. this._depthCullingState.zOffset = value;
  12695. };
  12696. Engine.prototype.getZOffset = function () {
  12697. return this._depthCullingState.zOffset;
  12698. };
  12699. Engine.prototype.setDepthBuffer = function (enable) {
  12700. this._depthCullingState.depthTest = enable;
  12701. };
  12702. Engine.prototype.getDepthWrite = function () {
  12703. return this._depthCullingState.depthMask;
  12704. };
  12705. Engine.prototype.setDepthWrite = function (enable) {
  12706. this._depthCullingState.depthMask = enable;
  12707. };
  12708. Engine.prototype.setColorWrite = function (enable) {
  12709. this._gl.colorMask(enable, enable, enable, enable);
  12710. this._colorWrite = enable;
  12711. };
  12712. Engine.prototype.getColorWrite = function () {
  12713. return this._colorWrite;
  12714. };
  12715. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12716. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12717. };
  12718. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12719. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12720. if (this._alphaMode === mode) {
  12721. return;
  12722. }
  12723. switch (mode) {
  12724. case Engine.ALPHA_DISABLE:
  12725. this._alphaState.alphaBlend = false;
  12726. break;
  12727. case Engine.ALPHA_PREMULTIPLIED:
  12728. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12729. this._alphaState.alphaBlend = true;
  12730. break;
  12731. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12732. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12733. this._alphaState.alphaBlend = true;
  12734. break;
  12735. case Engine.ALPHA_COMBINE:
  12736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12737. this._alphaState.alphaBlend = true;
  12738. break;
  12739. case Engine.ALPHA_ONEONE:
  12740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12741. this._alphaState.alphaBlend = true;
  12742. break;
  12743. case Engine.ALPHA_ADD:
  12744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12745. this._alphaState.alphaBlend = true;
  12746. break;
  12747. case Engine.ALPHA_SUBTRACT:
  12748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12749. this._alphaState.alphaBlend = true;
  12750. break;
  12751. case Engine.ALPHA_MULTIPLY:
  12752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12753. this._alphaState.alphaBlend = true;
  12754. break;
  12755. case Engine.ALPHA_MAXIMIZED:
  12756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12757. this._alphaState.alphaBlend = true;
  12758. break;
  12759. case Engine.ALPHA_INTERPOLATE:
  12760. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12761. this._alphaState.alphaBlend = true;
  12762. break;
  12763. case Engine.ALPHA_SCREENMODE:
  12764. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12765. this._alphaState.alphaBlend = true;
  12766. break;
  12767. }
  12768. if (!noDepthWriteChange) {
  12769. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12770. }
  12771. this._alphaMode = mode;
  12772. };
  12773. Engine.prototype.getAlphaMode = function () {
  12774. return this._alphaMode;
  12775. };
  12776. // Textures
  12777. Engine.prototype.wipeCaches = function (bruteForce) {
  12778. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12779. return;
  12780. }
  12781. this._currentEffect = null;
  12782. // 6/8/2017: deltakosh: Should not be required anymore.
  12783. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12784. if (bruteForce) {
  12785. this.resetTextureCache();
  12786. this._currentProgram = null;
  12787. this._stencilState.reset();
  12788. this._depthCullingState.reset();
  12789. this.setDepthFunctionToLessOrEqual();
  12790. this._alphaState.reset();
  12791. }
  12792. this._resetVertexBufferBinding();
  12793. this._cachedIndexBuffer = null;
  12794. this._cachedEffectForVertexBuffers = null;
  12795. this._unbindVertexArrayObject();
  12796. this.bindIndexBuffer(null);
  12797. };
  12798. /**
  12799. * Set the compressed texture format to use, based on the formats you have, and the formats
  12800. * supported by the hardware / browser.
  12801. *
  12802. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12803. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12804. * to API arguments needed to compressed textures. This puts the burden on the container
  12805. * generator to house the arcane code for determining these for current & future formats.
  12806. *
  12807. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12808. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12809. *
  12810. * Note: The result of this call is not taken into account when a texture is base64.
  12811. *
  12812. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12813. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12814. *
  12815. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12816. * @returns The extension selected.
  12817. */
  12818. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12819. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12820. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12821. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12822. return this._textureFormatInUse = this._texturesSupported[i];
  12823. }
  12824. }
  12825. }
  12826. // actively set format to nothing, to allow this to be called more than once
  12827. // and possibly fail the 2nd time
  12828. this._textureFormatInUse = null;
  12829. return null;
  12830. };
  12831. Engine.prototype._createTexture = function () {
  12832. var texture = this._gl.createTexture();
  12833. if (!texture) {
  12834. throw new Error("Unable to create texture");
  12835. }
  12836. return texture;
  12837. };
  12838. /**
  12839. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12840. * @param {string} urlArg- This contains one of the following:
  12841. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12842. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12843. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12844. *
  12845. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12846. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12847. * @param {Scene} scene- Needed for loading to the correct scene.
  12848. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12849. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12850. * @param {callback} onError- Optional callback to be called upon failure.
  12851. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12852. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12853. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12854. *
  12855. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12856. */
  12857. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12858. var _this = this;
  12859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12860. if (onLoad === void 0) { onLoad = null; }
  12861. if (onError === void 0) { onError = null; }
  12862. if (buffer === void 0) { buffer = null; }
  12863. if (fallBack === void 0) { fallBack = null; }
  12864. if (format === void 0) { format = null; }
  12865. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12866. var fromData = url.substr(0, 5) === "data:";
  12867. var fromBlob = url.substr(0, 5) === "blob:";
  12868. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12869. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12870. // establish the file extension, if possible
  12871. var lastDot = url.lastIndexOf('.');
  12872. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12873. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12874. var isTGA = (extension.indexOf(".tga") === 0);
  12875. // determine if a ktx file should be substituted
  12876. var isKTX = false;
  12877. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12878. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12879. isKTX = true;
  12880. }
  12881. if (scene) {
  12882. scene._addPendingData(texture);
  12883. }
  12884. texture.url = url;
  12885. texture.generateMipMaps = !noMipmap;
  12886. texture.samplingMode = samplingMode;
  12887. texture.invertY = invertY;
  12888. if (!this._doNotHandleContextLost) {
  12889. // Keep a link to the buffer only if we plan to handle context lost
  12890. texture._buffer = buffer;
  12891. }
  12892. var onLoadObserver = null;
  12893. if (onLoad && !fallBack) {
  12894. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12895. }
  12896. if (!fallBack)
  12897. this._internalTexturesCache.push(texture);
  12898. var onerror = function (message, exception) {
  12899. if (scene) {
  12900. scene._removePendingData(texture);
  12901. }
  12902. if (onLoadObserver) {
  12903. texture.onLoadedObservable.remove(onLoadObserver);
  12904. }
  12905. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12906. if (isKTX) {
  12907. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12908. }
  12909. else if (BABYLON.Tools.UseFallbackTexture) {
  12910. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12911. }
  12912. if (onError) {
  12913. onError(message || "Unknown error", exception);
  12914. }
  12915. };
  12916. var callback = null;
  12917. // processing for non-image formats
  12918. if (isKTX || isTGA || isDDS) {
  12919. if (isKTX) {
  12920. callback = function (data) {
  12921. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12922. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12923. ktx.uploadLevels(_this._gl, !noMipmap);
  12924. return false;
  12925. }, samplingMode);
  12926. };
  12927. }
  12928. else if (isTGA) {
  12929. callback = function (arrayBuffer) {
  12930. var data = new Uint8Array(arrayBuffer);
  12931. var header = BABYLON.TGATools.GetTGAHeader(data);
  12932. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12933. BABYLON.TGATools.UploadContent(_this._gl, data);
  12934. return false;
  12935. }, samplingMode);
  12936. };
  12937. }
  12938. else if (isDDS) {
  12939. callback = function (data) {
  12940. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12942. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12943. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12944. return false;
  12945. }, samplingMode);
  12946. };
  12947. }
  12948. if (!buffer) {
  12949. this._loadFile(url, function (data) {
  12950. if (callback) {
  12951. callback(data);
  12952. }
  12953. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12954. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12955. });
  12956. }
  12957. else {
  12958. if (callback) {
  12959. callback(buffer);
  12960. }
  12961. }
  12962. // image format processing
  12963. }
  12964. else {
  12965. var onload = function (img) {
  12966. if (fromBlob && !_this._doNotHandleContextLost) {
  12967. // We need to store the image if we need to rebuild the texture
  12968. // in case of a webgl context lost
  12969. texture._buffer = img;
  12970. }
  12971. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12972. var gl = _this._gl;
  12973. var isPot = (img.width === potWidth && img.height === potHeight);
  12974. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12975. if (isPot) {
  12976. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12977. return false;
  12978. }
  12979. // Using shaders to rescale because canvas.drawImage is lossy
  12980. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12981. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12982. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12987. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12988. _this._releaseTexture(source);
  12989. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12990. continuationCallback();
  12991. });
  12992. return true;
  12993. }, samplingMode);
  12994. };
  12995. if (!fromData || isBase64)
  12996. if (buffer instanceof HTMLImageElement) {
  12997. onload(buffer);
  12998. }
  12999. else {
  13000. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13001. }
  13002. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13003. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13004. else
  13005. onload(buffer);
  13006. }
  13007. return texture;
  13008. };
  13009. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13010. var _this = this;
  13011. var rtt = this.createRenderTargetTexture({
  13012. width: destination.width,
  13013. height: destination.height,
  13014. }, {
  13015. generateMipMaps: false,
  13016. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13017. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13018. generateDepthBuffer: false,
  13019. generateStencilBuffer: false
  13020. });
  13021. if (!this._rescalePostProcess) {
  13022. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13023. }
  13024. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13025. _this._rescalePostProcess.onApply = function (effect) {
  13026. effect._bindTexture("textureSampler", source);
  13027. };
  13028. var hostingScene = scene;
  13029. if (!hostingScene) {
  13030. hostingScene = _this.scenes[_this.scenes.length - 1];
  13031. }
  13032. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13033. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13034. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13035. _this.unBindFramebuffer(rtt);
  13036. _this._releaseTexture(rtt);
  13037. if (onComplete) {
  13038. onComplete();
  13039. }
  13040. });
  13041. };
  13042. Engine.prototype._getInternalFormat = function (format) {
  13043. var internalFormat = this._gl.RGBA;
  13044. switch (format) {
  13045. case Engine.TEXTUREFORMAT_ALPHA:
  13046. internalFormat = this._gl.ALPHA;
  13047. break;
  13048. case Engine.TEXTUREFORMAT_LUMINANCE:
  13049. internalFormat = this._gl.LUMINANCE;
  13050. break;
  13051. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13052. internalFormat = this._gl.LUMINANCE_ALPHA;
  13053. break;
  13054. case Engine.TEXTUREFORMAT_RGB:
  13055. case Engine.TEXTUREFORMAT_RGB32F:
  13056. internalFormat = this._gl.RGB;
  13057. break;
  13058. case Engine.TEXTUREFORMAT_RGBA:
  13059. case Engine.TEXTUREFORMAT_RGBA32F:
  13060. internalFormat = this._gl.RGBA;
  13061. break;
  13062. case Engine.TEXTUREFORMAT_R32F:
  13063. internalFormat = this._gl.RED;
  13064. break;
  13065. case Engine.TEXTUREFORMAT_RG32F:
  13066. internalFormat = this._gl.RG;
  13067. break;
  13068. }
  13069. return internalFormat;
  13070. };
  13071. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13072. if (compression === void 0) { compression = null; }
  13073. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13074. if (!texture) {
  13075. return;
  13076. }
  13077. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13078. var internalFormat = this._getInternalFormat(format);
  13079. var textureType = this._getWebGLTextureType(type);
  13080. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13081. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13082. if (!this._doNotHandleContextLost) {
  13083. texture._bufferView = data;
  13084. texture.format = format;
  13085. texture.type = type;
  13086. texture.invertY = invertY;
  13087. texture._compression = compression;
  13088. }
  13089. if (texture.width % 4 !== 0) {
  13090. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13091. }
  13092. if (compression && data) {
  13093. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13094. }
  13095. else {
  13096. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13097. }
  13098. if (texture.generateMipMaps) {
  13099. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13100. }
  13101. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13102. // this.resetTextureCache();
  13103. texture.isReady = true;
  13104. };
  13105. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13106. if (compression === void 0) { compression = null; }
  13107. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13108. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13109. texture.baseWidth = width;
  13110. texture.baseHeight = height;
  13111. texture.width = width;
  13112. texture.height = height;
  13113. texture.format = format;
  13114. texture.generateMipMaps = generateMipMaps;
  13115. texture.samplingMode = samplingMode;
  13116. texture.invertY = invertY;
  13117. texture._compression = compression;
  13118. texture.type = type;
  13119. if (!this._doNotHandleContextLost) {
  13120. texture._bufferView = data;
  13121. }
  13122. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13123. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13124. // Filters
  13125. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13126. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13128. if (generateMipMaps) {
  13129. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13130. }
  13131. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13132. this._internalTexturesCache.push(texture);
  13133. return texture;
  13134. };
  13135. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13136. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13137. texture.baseWidth = width;
  13138. texture.baseHeight = height;
  13139. if (generateMipMaps) {
  13140. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13141. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13142. }
  13143. // this.resetTextureCache();
  13144. texture.width = width;
  13145. texture.height = height;
  13146. texture.isReady = false;
  13147. texture.generateMipMaps = generateMipMaps;
  13148. texture.samplingMode = samplingMode;
  13149. this.updateTextureSamplingMode(samplingMode, texture);
  13150. this._internalTexturesCache.push(texture);
  13151. return texture;
  13152. };
  13153. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13154. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13155. if (texture.isCube) {
  13156. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13157. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13158. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13159. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13160. }
  13161. else if (texture.is3D) {
  13162. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13165. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13166. }
  13167. else {
  13168. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13170. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13171. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13172. }
  13173. texture.samplingMode = samplingMode;
  13174. };
  13175. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13176. if (premulAlpha === void 0) { premulAlpha = false; }
  13177. if (!texture) {
  13178. return;
  13179. }
  13180. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13181. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13182. if (premulAlpha) {
  13183. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13184. }
  13185. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13186. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13187. if (texture.generateMipMaps) {
  13188. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13189. }
  13190. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13191. if (premulAlpha) {
  13192. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13193. }
  13194. texture.isReady = true;
  13195. };
  13196. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13197. if (!texture || texture._isDisabled) {
  13198. return;
  13199. }
  13200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13201. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13202. try {
  13203. // Testing video texture support
  13204. if (this._videoTextureSupported === undefined) {
  13205. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13206. if (this._gl.getError() !== 0) {
  13207. this._videoTextureSupported = false;
  13208. }
  13209. else {
  13210. this._videoTextureSupported = true;
  13211. }
  13212. }
  13213. // Copy video through the current working canvas if video texture is not supported
  13214. if (!this._videoTextureSupported) {
  13215. if (!texture._workingCanvas) {
  13216. texture._workingCanvas = document.createElement("canvas");
  13217. var context = texture._workingCanvas.getContext("2d");
  13218. if (!context) {
  13219. throw new Error("Unable to get 2d context");
  13220. }
  13221. texture._workingContext = context;
  13222. texture._workingCanvas.width = texture.width;
  13223. texture._workingCanvas.height = texture.height;
  13224. }
  13225. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13227. }
  13228. else {
  13229. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13230. }
  13231. if (texture.generateMipMaps) {
  13232. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13233. }
  13234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13235. // this.resetTextureCache();
  13236. texture.isReady = true;
  13237. }
  13238. catch (ex) {
  13239. // Something unexpected
  13240. // Let's disable the texture
  13241. texture._isDisabled = true;
  13242. }
  13243. };
  13244. /**
  13245. * Updates a depth texture Comparison Mode and Function.
  13246. * If the comparison Function is equal to 0, the mode will be set to none.
  13247. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13248. * @param texture The texture to set the comparison function for
  13249. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13250. */
  13251. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13252. if (this.webGLVersion === 1) {
  13253. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13254. return;
  13255. }
  13256. var gl = this._gl;
  13257. if (texture.isCube) {
  13258. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13259. if (comparisonFunction === 0) {
  13260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13262. }
  13263. else {
  13264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13266. }
  13267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13268. }
  13269. else {
  13270. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13271. if (comparisonFunction === 0) {
  13272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13274. }
  13275. else {
  13276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13278. }
  13279. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13280. }
  13281. texture._comparisonFunction = comparisonFunction;
  13282. };
  13283. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13284. var width = size.width || size;
  13285. var height = size.height || size;
  13286. internalTexture.baseWidth = width;
  13287. internalTexture.baseHeight = height;
  13288. internalTexture.width = width;
  13289. internalTexture.height = height;
  13290. internalTexture.isReady = true;
  13291. internalTexture.samples = 1;
  13292. internalTexture.generateMipMaps = false;
  13293. internalTexture._generateDepthBuffer = true;
  13294. internalTexture._generateStencilBuffer = generateStencil;
  13295. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13296. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13297. internalTexture._comparisonFunction = comparisonFunction;
  13298. var gl = this._gl;
  13299. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13300. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13301. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13302. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13303. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13304. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13305. if (comparisonFunction === 0) {
  13306. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13307. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13308. }
  13309. else {
  13310. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13311. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13312. }
  13313. };
  13314. /**
  13315. * Creates a depth stencil texture.
  13316. * This is only available in WebGL 2 or with the depth texture extension available.
  13317. * @param size The size of face edge in the texture.
  13318. * @param options The options defining the texture.
  13319. * @returns The texture
  13320. */
  13321. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13322. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13323. if (!this._caps.depthTextureExtension) {
  13324. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13325. return internalTexture;
  13326. }
  13327. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13328. var gl = this._gl;
  13329. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13330. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13331. if (this.webGLVersion > 1) {
  13332. if (internalOptions.generateStencil) {
  13333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13334. }
  13335. else {
  13336. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13337. }
  13338. }
  13339. else {
  13340. if (internalOptions.generateStencil) {
  13341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13342. }
  13343. else {
  13344. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13345. }
  13346. }
  13347. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13348. return internalTexture;
  13349. };
  13350. /**
  13351. * Creates a depth stencil cube texture.
  13352. * This is only available in WebGL 2.
  13353. * @param size The size of face edge in the cube texture.
  13354. * @param options The options defining the cube texture.
  13355. * @returns The cube texture
  13356. */
  13357. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13358. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13359. internalTexture.isCube = true;
  13360. if (this.webGLVersion === 1) {
  13361. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13362. return internalTexture;
  13363. }
  13364. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13365. var gl = this._gl;
  13366. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13367. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13368. // Create the depth/stencil buffer
  13369. for (var face = 0; face < 6; face++) {
  13370. if (internalOptions.generateStencil) {
  13371. 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);
  13372. }
  13373. else {
  13374. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13375. }
  13376. }
  13377. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13378. return internalTexture;
  13379. };
  13380. /**
  13381. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13382. * @param renderTarget The render target to set the frame buffer for
  13383. */
  13384. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13385. // Create the framebuffer
  13386. var internalTexture = renderTarget.getInternalTexture();
  13387. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13388. return;
  13389. }
  13390. var gl = this._gl;
  13391. var depthStencilTexture = renderTarget.depthStencilTexture;
  13392. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13393. if (depthStencilTexture.isCube) {
  13394. if (depthStencilTexture._generateStencilBuffer) {
  13395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13396. }
  13397. else {
  13398. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13399. }
  13400. }
  13401. else {
  13402. if (depthStencilTexture._generateStencilBuffer) {
  13403. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13404. }
  13405. else {
  13406. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13407. }
  13408. }
  13409. this.bindUnboundFramebuffer(null);
  13410. };
  13411. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13412. var fullOptions = new RenderTargetCreationOptions();
  13413. if (options !== undefined && typeof options === "object") {
  13414. fullOptions.generateMipMaps = options.generateMipMaps;
  13415. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13416. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13417. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13418. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13419. }
  13420. else {
  13421. fullOptions.generateMipMaps = options;
  13422. fullOptions.generateDepthBuffer = true;
  13423. fullOptions.generateStencilBuffer = false;
  13424. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13425. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13426. }
  13427. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13428. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13429. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13430. }
  13431. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13432. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13433. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13434. }
  13435. var gl = this._gl;
  13436. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13437. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13438. var width = size.width || size;
  13439. var height = size.height || size;
  13440. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13441. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13442. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13443. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13444. }
  13445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13449. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13450. // Create the framebuffer
  13451. var framebuffer = gl.createFramebuffer();
  13452. this.bindUnboundFramebuffer(framebuffer);
  13453. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13454. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13455. if (fullOptions.generateMipMaps) {
  13456. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13457. }
  13458. // Unbind
  13459. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13461. this.bindUnboundFramebuffer(null);
  13462. texture._framebuffer = framebuffer;
  13463. texture.baseWidth = width;
  13464. texture.baseHeight = height;
  13465. texture.width = width;
  13466. texture.height = height;
  13467. texture.isReady = true;
  13468. texture.samples = 1;
  13469. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13470. texture.samplingMode = fullOptions.samplingMode;
  13471. texture.type = fullOptions.type;
  13472. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13473. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13474. // this.resetTextureCache();
  13475. this._internalTexturesCache.push(texture);
  13476. return texture;
  13477. };
  13478. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13479. var generateMipMaps = false;
  13480. var generateDepthBuffer = true;
  13481. var generateStencilBuffer = false;
  13482. var generateDepthTexture = false;
  13483. var textureCount = 1;
  13484. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13485. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13486. var types = [], samplingModes = [];
  13487. if (options !== undefined) {
  13488. generateMipMaps = options.generateMipMaps;
  13489. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13490. generateStencilBuffer = options.generateStencilBuffer;
  13491. generateDepthTexture = options.generateDepthTexture;
  13492. textureCount = options.textureCount || 1;
  13493. if (options.types) {
  13494. types = options.types;
  13495. }
  13496. if (options.samplingModes) {
  13497. samplingModes = options.samplingModes;
  13498. }
  13499. }
  13500. var gl = this._gl;
  13501. // Create the framebuffer
  13502. var framebuffer = gl.createFramebuffer();
  13503. this.bindUnboundFramebuffer(framebuffer);
  13504. var width = size.width || size;
  13505. var height = size.height || size;
  13506. var textures = [];
  13507. var attachments = [];
  13508. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13509. for (var i = 0; i < textureCount; i++) {
  13510. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13511. var type = types[i] || defaultType;
  13512. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13513. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13514. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13515. }
  13516. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13517. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13518. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13519. }
  13520. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13521. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13522. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13523. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13524. }
  13525. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13526. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13527. textures.push(texture);
  13528. attachments.push(attachment);
  13529. gl.activeTexture(gl["TEXTURE" + i]);
  13530. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13535. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13536. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13537. if (generateMipMaps) {
  13538. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13539. }
  13540. // Unbind
  13541. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13542. texture._framebuffer = framebuffer;
  13543. texture._depthStencilBuffer = depthStencilBuffer;
  13544. texture.baseWidth = width;
  13545. texture.baseHeight = height;
  13546. texture.width = width;
  13547. texture.height = height;
  13548. texture.isReady = true;
  13549. texture.samples = 1;
  13550. texture.generateMipMaps = generateMipMaps;
  13551. texture.samplingMode = samplingMode;
  13552. texture.type = type;
  13553. texture._generateDepthBuffer = generateDepthBuffer;
  13554. texture._generateStencilBuffer = generateStencilBuffer;
  13555. texture._attachments = attachments;
  13556. this._internalTexturesCache.push(texture);
  13557. }
  13558. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13559. // Depth texture
  13560. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13561. gl.activeTexture(gl.TEXTURE0);
  13562. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13565. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13567. 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);
  13568. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13569. depthTexture._framebuffer = framebuffer;
  13570. depthTexture.baseWidth = width;
  13571. depthTexture.baseHeight = height;
  13572. depthTexture.width = width;
  13573. depthTexture.height = height;
  13574. depthTexture.isReady = true;
  13575. depthTexture.samples = 1;
  13576. depthTexture.generateMipMaps = generateMipMaps;
  13577. depthTexture.samplingMode = gl.NEAREST;
  13578. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13579. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13580. textures.push(depthTexture);
  13581. this._internalTexturesCache.push(depthTexture);
  13582. }
  13583. gl.drawBuffers(attachments);
  13584. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13585. this.bindUnboundFramebuffer(null);
  13586. this.resetTextureCache();
  13587. return textures;
  13588. };
  13589. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13590. if (samples === void 0) { samples = 1; }
  13591. var depthStencilBuffer = null;
  13592. var gl = this._gl;
  13593. // Create the depth/stencil buffer
  13594. if (generateStencilBuffer) {
  13595. depthStencilBuffer = gl.createRenderbuffer();
  13596. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13597. if (samples > 1) {
  13598. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13599. }
  13600. else {
  13601. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13602. }
  13603. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13604. }
  13605. else if (generateDepthBuffer) {
  13606. depthStencilBuffer = gl.createRenderbuffer();
  13607. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13608. if (samples > 1) {
  13609. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13610. }
  13611. else {
  13612. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13613. }
  13614. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13615. }
  13616. return depthStencilBuffer;
  13617. };
  13618. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13619. if (this.webGLVersion < 2 || !texture) {
  13620. return 1;
  13621. }
  13622. if (texture.samples === samples) {
  13623. return samples;
  13624. }
  13625. var gl = this._gl;
  13626. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13627. // Dispose previous render buffers
  13628. if (texture._depthStencilBuffer) {
  13629. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13630. texture._depthStencilBuffer = null;
  13631. }
  13632. if (texture._MSAAFramebuffer) {
  13633. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13634. texture._MSAAFramebuffer = null;
  13635. }
  13636. if (texture._MSAARenderBuffer) {
  13637. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13638. texture._MSAARenderBuffer = null;
  13639. }
  13640. if (samples > 1) {
  13641. var framebuffer = gl.createFramebuffer();
  13642. if (!framebuffer) {
  13643. throw new Error("Unable to create multi sampled framebuffer");
  13644. }
  13645. texture._MSAAFramebuffer = framebuffer;
  13646. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13647. var colorRenderbuffer = gl.createRenderbuffer();
  13648. if (!colorRenderbuffer) {
  13649. throw new Error("Unable to create multi sampled framebuffer");
  13650. }
  13651. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13652. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13654. texture._MSAARenderBuffer = colorRenderbuffer;
  13655. }
  13656. else {
  13657. this.bindUnboundFramebuffer(texture._framebuffer);
  13658. }
  13659. texture.samples = samples;
  13660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13661. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13662. this.bindUnboundFramebuffer(null);
  13663. return samples;
  13664. };
  13665. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13666. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13667. return 1;
  13668. }
  13669. if (textures[0].samples === samples) {
  13670. return samples;
  13671. }
  13672. var gl = this._gl;
  13673. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13674. // Dispose previous render buffers
  13675. if (textures[0]._depthStencilBuffer) {
  13676. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13677. textures[0]._depthStencilBuffer = null;
  13678. }
  13679. if (textures[0]._MSAAFramebuffer) {
  13680. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13681. textures[0]._MSAAFramebuffer = null;
  13682. }
  13683. for (var i = 0; i < textures.length; i++) {
  13684. if (textures[i]._MSAARenderBuffer) {
  13685. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13686. textures[i]._MSAARenderBuffer = null;
  13687. }
  13688. }
  13689. if (samples > 1) {
  13690. var framebuffer = gl.createFramebuffer();
  13691. if (!framebuffer) {
  13692. throw new Error("Unable to create multi sampled framebuffer");
  13693. }
  13694. this.bindUnboundFramebuffer(framebuffer);
  13695. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13696. var attachments = [];
  13697. for (var i = 0; i < textures.length; i++) {
  13698. var texture = textures[i];
  13699. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13700. var colorRenderbuffer = gl.createRenderbuffer();
  13701. if (!colorRenderbuffer) {
  13702. throw new Error("Unable to create multi sampled framebuffer");
  13703. }
  13704. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13705. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13706. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13707. texture._MSAAFramebuffer = framebuffer;
  13708. texture._MSAARenderBuffer = colorRenderbuffer;
  13709. texture.samples = samples;
  13710. texture._depthStencilBuffer = depthStencilBuffer;
  13711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13712. attachments.push(attachment);
  13713. }
  13714. gl.drawBuffers(attachments);
  13715. }
  13716. else {
  13717. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13718. }
  13719. this.bindUnboundFramebuffer(null);
  13720. return samples;
  13721. };
  13722. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13723. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13724. };
  13725. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13726. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13727. };
  13728. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13729. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13730. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13731. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13732. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13733. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13734. }
  13735. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13736. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13737. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13738. }
  13739. var gl = this._gl;
  13740. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13741. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13742. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13744. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13745. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13746. }
  13747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13751. for (var face = 0; face < 6; face++) {
  13752. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13753. }
  13754. // Create the framebuffer
  13755. var framebuffer = gl.createFramebuffer();
  13756. this.bindUnboundFramebuffer(framebuffer);
  13757. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13758. // MipMaps
  13759. if (fullOptions.generateMipMaps) {
  13760. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13761. }
  13762. // Unbind
  13763. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. texture._framebuffer = framebuffer;
  13767. texture.width = size;
  13768. texture.height = size;
  13769. texture.isReady = true;
  13770. texture.isCube = true;
  13771. texture.samples = 1;
  13772. texture.generateMipMaps = fullOptions.generateMipMaps;
  13773. texture.samplingMode = fullOptions.samplingMode;
  13774. texture.type = fullOptions.type;
  13775. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13776. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13777. this._internalTexturesCache.push(texture);
  13778. return texture;
  13779. };
  13780. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13781. var _this = this;
  13782. if (onLoad === void 0) { onLoad = null; }
  13783. if (onError === void 0) { onError = null; }
  13784. if (forcedExtension === void 0) { forcedExtension = null; }
  13785. var callback = function (loadData) {
  13786. if (!loadData) {
  13787. if (onLoad) {
  13788. onLoad(null);
  13789. }
  13790. return;
  13791. }
  13792. var texture = loadData.texture;
  13793. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13794. texture._lodGenerationScale = scale;
  13795. texture._lodGenerationOffset = offset;
  13796. if (_this._caps.textureLOD) {
  13797. // Do not add extra process if texture lod is supported.
  13798. if (onLoad) {
  13799. onLoad(texture);
  13800. }
  13801. return;
  13802. }
  13803. var mipSlices = 3;
  13804. var gl = _this._gl;
  13805. var width = loadData.width;
  13806. if (!width) {
  13807. return;
  13808. }
  13809. var textures = [];
  13810. for (var i = 0; i < mipSlices; i++) {
  13811. //compute LOD from even spacing in smoothness (matching shader calculation)
  13812. var smoothness = i / (mipSlices - 1);
  13813. var roughness = 1 - smoothness;
  13814. var minLODIndex = offset; // roughness = 0
  13815. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13816. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13817. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13818. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13819. glTextureFromLod.isCube = true;
  13820. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13825. if (loadData.isDDS) {
  13826. var info = loadData.info;
  13827. var data = loadData.data;
  13828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13829. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13830. }
  13831. else {
  13832. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13833. }
  13834. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13835. // Wrap in a base texture for easy binding.
  13836. var lodTexture = new BABYLON.BaseTexture(scene);
  13837. lodTexture.isCube = true;
  13838. lodTexture._texture = glTextureFromLod;
  13839. glTextureFromLod.isReady = true;
  13840. textures.push(lodTexture);
  13841. }
  13842. texture._lodTextureHigh = textures[2];
  13843. texture._lodTextureMid = textures[1];
  13844. texture._lodTextureLow = textures[0];
  13845. if (onLoad) {
  13846. onLoad(texture);
  13847. }
  13848. };
  13849. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13850. };
  13851. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13852. var _this = this;
  13853. if (onLoad === void 0) { onLoad = null; }
  13854. if (onError === void 0) { onError = null; }
  13855. if (forcedExtension === void 0) { forcedExtension = null; }
  13856. var gl = this._gl;
  13857. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13858. texture.isCube = true;
  13859. texture.url = rootUrl;
  13860. texture.generateMipMaps = !noMipmap;
  13861. if (!this._doNotHandleContextLost) {
  13862. texture._extension = forcedExtension;
  13863. texture._files = files;
  13864. }
  13865. var isKTX = false;
  13866. var isDDS = false;
  13867. var lastDot = rootUrl.lastIndexOf('.');
  13868. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13869. if (this._textureFormatInUse) {
  13870. extension = this._textureFormatInUse;
  13871. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13872. isKTX = true;
  13873. }
  13874. else {
  13875. isDDS = (extension === ".dds");
  13876. }
  13877. var onerror = function (request, exception) {
  13878. if (onError && request) {
  13879. onError(request.status + " " + request.statusText, exception);
  13880. }
  13881. };
  13882. if (isKTX) {
  13883. this._loadFile(rootUrl, function (data) {
  13884. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13885. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13888. ktx.uploadLevels(_this._gl, !noMipmap);
  13889. _this.setCubeMapTextureParams(gl, loadMipmap);
  13890. texture.width = ktx.pixelWidth;
  13891. texture.height = ktx.pixelHeight;
  13892. texture.isReady = true;
  13893. }, undefined, undefined, true, onerror);
  13894. }
  13895. else if (isDDS) {
  13896. if (files && files.length === 6) {
  13897. this._cascadeLoadFiles(scene, function (imgs) {
  13898. var info;
  13899. var loadMipmap = false;
  13900. var width = 0;
  13901. for (var index = 0; index < imgs.length; index++) {
  13902. var data = imgs[index];
  13903. info = BABYLON.DDSTools.GetDDSInfo(data);
  13904. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13907. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13908. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13910. }
  13911. texture.width = info.width;
  13912. texture.height = info.height;
  13913. texture.type = info.textureType;
  13914. width = info.width;
  13915. }
  13916. _this.setCubeMapTextureParams(gl, loadMipmap);
  13917. texture.isReady = true;
  13918. if (onLoad) {
  13919. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13920. }
  13921. }, files, onError);
  13922. }
  13923. else {
  13924. this._loadFile(rootUrl, function (data) {
  13925. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13926. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13927. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13928. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13929. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13930. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13931. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13932. }
  13933. _this.setCubeMapTextureParams(gl, loadMipmap);
  13934. texture.width = info.width;
  13935. texture.height = info.height;
  13936. texture.isReady = true;
  13937. texture.type = info.textureType;
  13938. if (onLoad) {
  13939. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13940. }
  13941. }, undefined, undefined, true, onerror);
  13942. }
  13943. }
  13944. else {
  13945. if (!files) {
  13946. throw new Error("Cannot load cubemap because files were not defined");
  13947. }
  13948. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13949. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13950. var height = width;
  13951. _this._prepareWorkingCanvas();
  13952. if (!_this._workingCanvas || !_this._workingContext) {
  13953. return;
  13954. }
  13955. _this._workingCanvas.width = width;
  13956. _this._workingCanvas.height = height;
  13957. var faces = [
  13958. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13959. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13960. ];
  13961. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13963. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13964. for (var index = 0; index < faces.length; index++) {
  13965. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13966. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13967. }
  13968. if (!noMipmap) {
  13969. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13970. }
  13971. _this.setCubeMapTextureParams(gl, !noMipmap);
  13972. texture.width = width;
  13973. texture.height = height;
  13974. texture.isReady = true;
  13975. if (format) {
  13976. texture.format = format;
  13977. }
  13978. texture.onLoadedObservable.notifyObservers(texture);
  13979. texture.onLoadedObservable.clear();
  13980. if (onLoad) {
  13981. onLoad();
  13982. }
  13983. }, files, onError);
  13984. }
  13985. this._internalTexturesCache.push(texture);
  13986. return texture;
  13987. };
  13988. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13991. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13993. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13994. // this.resetTextureCache();
  13995. };
  13996. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13997. if (compression === void 0) { compression = null; }
  13998. if (level === void 0) { level = 0; }
  13999. texture._bufferViewArray = data;
  14000. texture.format = format;
  14001. texture.type = type;
  14002. texture.invertY = invertY;
  14003. texture._compression = compression;
  14004. var gl = this._gl;
  14005. var textureType = this._getWebGLTextureType(type);
  14006. var internalFormat = this._getInternalFormat(format);
  14007. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14008. var needConversion = false;
  14009. if (internalFormat === gl.RGB) {
  14010. internalFormat = gl.RGBA;
  14011. needConversion = true;
  14012. }
  14013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14014. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14015. if (texture.width % 4 !== 0) {
  14016. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14017. }
  14018. // Data are known to be in +X +Y +Z -X -Y -Z
  14019. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14020. var faceData = data[faceIndex];
  14021. if (compression) {
  14022. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14023. }
  14024. else {
  14025. if (needConversion) {
  14026. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14027. }
  14028. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14029. }
  14030. }
  14031. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14032. if (isPot && texture.generateMipMaps && level === 0) {
  14033. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14034. }
  14035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14036. // this.resetTextureCache();
  14037. texture.isReady = true;
  14038. };
  14039. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14040. if (compression === void 0) { compression = null; }
  14041. var gl = this._gl;
  14042. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14043. texture.isCube = true;
  14044. texture.generateMipMaps = generateMipMaps;
  14045. texture.format = format;
  14046. texture.type = type;
  14047. if (!this._doNotHandleContextLost) {
  14048. texture._bufferViewArray = data;
  14049. }
  14050. var textureType = this._getWebGLTextureType(type);
  14051. var internalFormat = this._getInternalFormat(format);
  14052. if (internalFormat === gl.RGB) {
  14053. internalFormat = gl.RGBA;
  14054. }
  14055. var width = size;
  14056. var height = width;
  14057. texture.width = width;
  14058. texture.height = height;
  14059. // Double check on POT to generate Mips.
  14060. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14061. if (!isPot) {
  14062. generateMipMaps = false;
  14063. }
  14064. // Upload data if needed. The texture won't be ready until then.
  14065. if (data) {
  14066. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14067. }
  14068. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14069. // Filters
  14070. if (data && generateMipMaps) {
  14071. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14072. }
  14073. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14076. }
  14077. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14080. }
  14081. else {
  14082. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14085. }
  14086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14088. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14089. return texture;
  14090. };
  14091. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14092. var _this = this;
  14093. if (onLoad === void 0) { onLoad = null; }
  14094. if (onError === void 0) { onError = null; }
  14095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14096. if (invertY === void 0) { invertY = false; }
  14097. var gl = this._gl;
  14098. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14099. scene._addPendingData(texture);
  14100. texture.url = url;
  14101. this._internalTexturesCache.push(texture);
  14102. var onerror = function (request, exception) {
  14103. scene._removePendingData(texture);
  14104. if (onError && request) {
  14105. onError(request.status + " " + request.statusText, exception);
  14106. }
  14107. };
  14108. var internalCallback = function (data) {
  14109. var width = texture.width;
  14110. var faceDataArrays = callback(data);
  14111. if (!faceDataArrays) {
  14112. return;
  14113. }
  14114. if (mipmmapGenerator) {
  14115. var textureType = _this._getWebGLTextureType(type);
  14116. var internalFormat = _this._getInternalFormat(format);
  14117. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14118. var needConversion = false;
  14119. if (internalFormat === gl.RGB) {
  14120. internalFormat = gl.RGBA;
  14121. needConversion = true;
  14122. }
  14123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14124. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14125. var mipData = mipmmapGenerator(faceDataArrays);
  14126. for (var level = 0; level < mipData.length; level++) {
  14127. var mipSize = width >> level;
  14128. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14129. var mipFaceData = mipData[level][faceIndex];
  14130. if (needConversion) {
  14131. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14132. }
  14133. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14134. }
  14135. }
  14136. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14137. }
  14138. else {
  14139. texture.generateMipMaps = !noMipmap;
  14140. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14141. }
  14142. texture.isReady = true;
  14143. // this.resetTextureCache();
  14144. scene._removePendingData(texture);
  14145. if (onLoad) {
  14146. onLoad();
  14147. }
  14148. };
  14149. this._loadFile(url, function (data) {
  14150. internalCallback(data);
  14151. }, undefined, scene.database, true, onerror);
  14152. return texture;
  14153. };
  14154. ;
  14155. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14156. if (compression === void 0) { compression = null; }
  14157. var internalFormat = this._getInternalFormat(format);
  14158. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14160. if (!this._doNotHandleContextLost) {
  14161. texture._bufferView = data;
  14162. texture.format = format;
  14163. texture.invertY = invertY;
  14164. texture._compression = compression;
  14165. }
  14166. if (texture.width % 4 !== 0) {
  14167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14168. }
  14169. if (compression && data) {
  14170. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14171. }
  14172. else {
  14173. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14174. }
  14175. if (texture.generateMipMaps) {
  14176. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14177. }
  14178. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14179. // this.resetTextureCache();
  14180. texture.isReady = true;
  14181. };
  14182. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14183. if (compression === void 0) { compression = null; }
  14184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14185. texture.baseWidth = width;
  14186. texture.baseHeight = height;
  14187. texture.baseDepth = depth;
  14188. texture.width = width;
  14189. texture.height = height;
  14190. texture.depth = depth;
  14191. texture.format = format;
  14192. texture.generateMipMaps = generateMipMaps;
  14193. texture.samplingMode = samplingMode;
  14194. texture.is3D = true;
  14195. if (!this._doNotHandleContextLost) {
  14196. texture._bufferView = data;
  14197. }
  14198. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14200. // Filters
  14201. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14204. if (generateMipMaps) {
  14205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14206. }
  14207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14208. this._internalTexturesCache.push(texture);
  14209. return texture;
  14210. };
  14211. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14212. var gl = this._gl;
  14213. if (!gl) {
  14214. return;
  14215. }
  14216. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14219. if (!noMipmap && !isCompressed) {
  14220. gl.generateMipmap(gl.TEXTURE_2D);
  14221. }
  14222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14223. // this.resetTextureCache();
  14224. if (scene) {
  14225. scene._removePendingData(texture);
  14226. }
  14227. texture.onLoadedObservable.notifyObservers(texture);
  14228. texture.onLoadedObservable.clear();
  14229. };
  14230. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14231. var _this = this;
  14232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14233. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14234. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14235. var gl = this._gl;
  14236. if (!gl) {
  14237. return;
  14238. }
  14239. if (!texture._webGLTexture) {
  14240. // this.resetTextureCache();
  14241. if (scene) {
  14242. scene._removePendingData(texture);
  14243. }
  14244. return;
  14245. }
  14246. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14248. texture.baseWidth = width;
  14249. texture.baseHeight = height;
  14250. texture.width = potWidth;
  14251. texture.height = potHeight;
  14252. texture.isReady = true;
  14253. if (processFunction(potWidth, potHeight, function () {
  14254. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14255. })) {
  14256. // Returning as texture needs extra async steps
  14257. return;
  14258. }
  14259. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14260. };
  14261. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14262. // Create new RGBA data container.
  14263. var rgbaData;
  14264. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14265. rgbaData = new Float32Array(width * height * 4);
  14266. }
  14267. else {
  14268. rgbaData = new Uint32Array(width * height * 4);
  14269. }
  14270. // Convert each pixel.
  14271. for (var x = 0; x < width; x++) {
  14272. for (var y = 0; y < height; y++) {
  14273. var index = (y * width + x) * 3;
  14274. var newIndex = (y * width + x) * 4;
  14275. // Map Old Value to new value.
  14276. rgbaData[newIndex + 0] = rgbData[index + 0];
  14277. rgbaData[newIndex + 1] = rgbData[index + 1];
  14278. rgbaData[newIndex + 2] = rgbData[index + 2];
  14279. // Add fully opaque alpha channel.
  14280. rgbaData[newIndex + 3] = 1;
  14281. }
  14282. }
  14283. return rgbaData;
  14284. };
  14285. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14286. var gl = this._gl;
  14287. if (texture._framebuffer) {
  14288. gl.deleteFramebuffer(texture._framebuffer);
  14289. texture._framebuffer = null;
  14290. }
  14291. if (texture._depthStencilBuffer) {
  14292. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14293. texture._depthStencilBuffer = null;
  14294. }
  14295. if (texture._MSAAFramebuffer) {
  14296. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14297. texture._MSAAFramebuffer = null;
  14298. }
  14299. if (texture._MSAARenderBuffer) {
  14300. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14301. texture._MSAARenderBuffer = null;
  14302. }
  14303. };
  14304. Engine.prototype._releaseTexture = function (texture) {
  14305. var gl = this._gl;
  14306. this._releaseFramebufferObjects(texture);
  14307. gl.deleteTexture(texture._webGLTexture);
  14308. // Unbind channels
  14309. this.unbindAllTextures();
  14310. var index = this._internalTexturesCache.indexOf(texture);
  14311. if (index !== -1) {
  14312. this._internalTexturesCache.splice(index, 1);
  14313. }
  14314. // Integrated fixed lod samplers.
  14315. if (texture._lodTextureHigh) {
  14316. texture._lodTextureHigh.dispose();
  14317. }
  14318. if (texture._lodTextureMid) {
  14319. texture._lodTextureMid.dispose();
  14320. }
  14321. if (texture._lodTextureLow) {
  14322. texture._lodTextureLow.dispose();
  14323. }
  14324. };
  14325. Engine.prototype.setProgram = function (program) {
  14326. if (this._currentProgram !== program) {
  14327. this._gl.useProgram(program);
  14328. this._currentProgram = program;
  14329. }
  14330. };
  14331. Engine.prototype.bindSamplers = function (effect) {
  14332. this.setProgram(effect.getProgram());
  14333. var samplers = effect.getSamplers();
  14334. for (var index = 0; index < samplers.length; index++) {
  14335. var uniform = effect.getUniform(samplers[index]);
  14336. if (uniform) {
  14337. this._boundUniforms[index] = uniform;
  14338. }
  14339. }
  14340. this._currentEffect = null;
  14341. };
  14342. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14343. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14344. return;
  14345. }
  14346. // Remove
  14347. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14348. // Bind last to it
  14349. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14350. // Bind to dummy
  14351. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14352. };
  14353. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14354. if (!internalTexture) {
  14355. return -1;
  14356. }
  14357. internalTexture._initialSlot = channel;
  14358. if (this.disableTextureBindingOptimization) {
  14359. if (channel !== internalTexture._designatedSlot) {
  14360. this._textureCollisions.addCount(1, false);
  14361. }
  14362. }
  14363. else {
  14364. if (channel !== internalTexture._designatedSlot) {
  14365. if (internalTexture._designatedSlot > -1) {
  14366. return internalTexture._designatedSlot;
  14367. }
  14368. else {
  14369. // No slot for this texture, let's pick a new one (if we find a free slot)
  14370. if (this._nextFreeTextureSlots.length) {
  14371. return this._nextFreeTextureSlots[0];
  14372. }
  14373. // We need to recycle the oldest bound texture, sorry.
  14374. this._textureCollisions.addCount(1, false);
  14375. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14376. }
  14377. }
  14378. }
  14379. return channel;
  14380. };
  14381. Engine.prototype._linkTrackers = function (previous, next) {
  14382. previous.next = next;
  14383. next.previous = previous;
  14384. };
  14385. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14386. var currentSlot = internalTexture._designatedSlot;
  14387. if (currentSlot === -1) {
  14388. return -1;
  14389. }
  14390. internalTexture._designatedSlot = -1;
  14391. if (this.disableTextureBindingOptimization) {
  14392. return -1;
  14393. }
  14394. // Remove from bound list
  14395. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14396. // Free the slot
  14397. this._boundTexturesCache[currentSlot] = null;
  14398. this._nextFreeTextureSlots.push(currentSlot);
  14399. return currentSlot;
  14400. };
  14401. Engine.prototype._activateCurrentTexture = function () {
  14402. if (this._currentTextureChannel !== this._activeChannel) {
  14403. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14404. this._currentTextureChannel = this._activeChannel;
  14405. }
  14406. };
  14407. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14408. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14409. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14410. this._activeChannel = texture._designatedSlot;
  14411. }
  14412. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14413. var isTextureForRendering = texture && texture._initialSlot > -1;
  14414. if (currentTextureBound !== texture) {
  14415. if (currentTextureBound) {
  14416. this._removeDesignatedSlot(currentTextureBound);
  14417. }
  14418. this._activateCurrentTexture();
  14419. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14420. this._boundTexturesCache[this._activeChannel] = texture;
  14421. if (texture) {
  14422. if (!this.disableTextureBindingOptimization) {
  14423. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14424. if (slotIndex > -1) {
  14425. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14426. }
  14427. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14428. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14429. }
  14430. texture._designatedSlot = this._activeChannel;
  14431. }
  14432. }
  14433. else if (forTextureDataUpdate) {
  14434. this._activateCurrentTexture();
  14435. }
  14436. if (isTextureForRendering && !forTextureDataUpdate) {
  14437. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14438. }
  14439. };
  14440. Engine.prototype._bindTexture = function (channel, texture) {
  14441. if (channel < 0) {
  14442. return;
  14443. }
  14444. if (texture) {
  14445. channel = this._getCorrectTextureChannel(channel, texture);
  14446. }
  14447. this._activeChannel = channel;
  14448. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14449. };
  14450. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14451. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14452. };
  14453. Engine.prototype.unbindAllTextures = function () {
  14454. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14455. this._activeChannel = channel;
  14456. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14457. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14458. if (this.webGLVersion > 1) {
  14459. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14460. }
  14461. }
  14462. };
  14463. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14464. if (channel < 0) {
  14465. return;
  14466. }
  14467. if (uniform) {
  14468. this._boundUniforms[channel] = uniform;
  14469. }
  14470. this._setTexture(channel, texture);
  14471. };
  14472. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14473. var uniform = this._boundUniforms[sourceSlot];
  14474. if (uniform._currentState === destination) {
  14475. return;
  14476. }
  14477. this._gl.uniform1i(uniform, destination);
  14478. uniform._currentState = destination;
  14479. };
  14480. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14481. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14482. // Not ready?
  14483. if (!texture) {
  14484. if (this._boundTexturesCache[channel] != null) {
  14485. this._activeChannel = channel;
  14486. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14488. if (this.webGLVersion > 1) {
  14489. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14490. }
  14491. }
  14492. return false;
  14493. }
  14494. // Video
  14495. if (texture.video) {
  14496. this._activeChannel = channel;
  14497. texture.update();
  14498. }
  14499. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14500. texture.delayLoad();
  14501. return false;
  14502. }
  14503. var internalTexture;
  14504. if (texture.isReady()) {
  14505. internalTexture = texture.getInternalTexture();
  14506. }
  14507. else if (texture.isCube) {
  14508. internalTexture = this.emptyCubeTexture;
  14509. }
  14510. else if (texture.is3D) {
  14511. internalTexture = this.emptyTexture3D;
  14512. }
  14513. else {
  14514. internalTexture = this.emptyTexture;
  14515. }
  14516. if (!isPartOfTextureArray) {
  14517. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14518. }
  14519. if (this._boundTexturesCache[channel] === internalTexture) {
  14520. this._moveBoundTextureOnTop(internalTexture);
  14521. if (!isPartOfTextureArray) {
  14522. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14523. }
  14524. return false;
  14525. }
  14526. this._activeChannel = channel;
  14527. if (internalTexture && internalTexture.is3D) {
  14528. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14529. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14530. internalTexture._cachedWrapU = texture.wrapU;
  14531. switch (texture.wrapU) {
  14532. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14533. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14534. break;
  14535. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14537. break;
  14538. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14540. break;
  14541. }
  14542. }
  14543. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14544. internalTexture._cachedWrapV = texture.wrapV;
  14545. switch (texture.wrapV) {
  14546. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14547. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14548. break;
  14549. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14550. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14551. break;
  14552. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14553. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14554. break;
  14555. }
  14556. }
  14557. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14558. internalTexture._cachedWrapR = texture.wrapR;
  14559. switch (texture.wrapR) {
  14560. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14561. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14562. break;
  14563. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14564. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14565. break;
  14566. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14567. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14568. break;
  14569. }
  14570. }
  14571. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14572. }
  14573. else if (internalTexture && internalTexture.isCube) {
  14574. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14575. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14576. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14577. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14578. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14579. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14580. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14581. }
  14582. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14583. }
  14584. else {
  14585. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14586. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14587. internalTexture._cachedWrapU = texture.wrapU;
  14588. switch (texture.wrapU) {
  14589. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14590. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14591. break;
  14592. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14593. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14594. break;
  14595. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14597. break;
  14598. }
  14599. }
  14600. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14601. internalTexture._cachedWrapV = texture.wrapV;
  14602. switch (texture.wrapV) {
  14603. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14604. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14605. break;
  14606. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14608. break;
  14609. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14611. break;
  14612. }
  14613. }
  14614. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14615. }
  14616. return true;
  14617. };
  14618. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14619. if (channel < 0 || !uniform) {
  14620. return;
  14621. }
  14622. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14623. this._textureUnits = new Int32Array(textures.length);
  14624. }
  14625. for (var i = 0; i < textures.length; i++) {
  14626. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14627. }
  14628. this._gl.uniform1iv(uniform, this._textureUnits);
  14629. for (var index = 0; index < textures.length; index++) {
  14630. this._setTexture(this._textureUnits[index], textures[index], true);
  14631. }
  14632. };
  14633. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14634. var internalTexture = texture.getInternalTexture();
  14635. if (!internalTexture) {
  14636. return;
  14637. }
  14638. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14639. var value = texture.anisotropicFilteringLevel;
  14640. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14641. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14642. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14643. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14644. }
  14645. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14646. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14647. internalTexture._cachedAnisotropicFilteringLevel = value;
  14648. }
  14649. };
  14650. Engine.prototype.readPixels = function (x, y, width, height) {
  14651. var data = new Uint8Array(height * width * 4);
  14652. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14653. return data;
  14654. };
  14655. /**
  14656. * Add an externaly attached data from its key.
  14657. * This method call will fail and return false, if such key already exists.
  14658. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14659. * @param key the unique key that identifies the data
  14660. * @param data the data object to associate to the key for this Engine instance
  14661. * @return true if no such key were already present and the data was added successfully, false otherwise
  14662. */
  14663. Engine.prototype.addExternalData = function (key, data) {
  14664. if (!this._externalData) {
  14665. this._externalData = new BABYLON.StringDictionary();
  14666. }
  14667. return this._externalData.add(key, data);
  14668. };
  14669. /**
  14670. * Get an externaly attached data from its key
  14671. * @param key the unique key that identifies the data
  14672. * @return the associated data, if present (can be null), or undefined if not present
  14673. */
  14674. Engine.prototype.getExternalData = function (key) {
  14675. if (!this._externalData) {
  14676. this._externalData = new BABYLON.StringDictionary();
  14677. }
  14678. return this._externalData.get(key);
  14679. };
  14680. /**
  14681. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14682. * @param key the unique key that identifies the data
  14683. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14684. * @return the associated data, can be null if the factory returned null.
  14685. */
  14686. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14687. if (!this._externalData) {
  14688. this._externalData = new BABYLON.StringDictionary();
  14689. }
  14690. return this._externalData.getOrAddWithFactory(key, factory);
  14691. };
  14692. /**
  14693. * Remove an externaly attached data from the Engine instance
  14694. * @param key the unique key that identifies the data
  14695. * @return true if the data was successfully removed, false if it doesn't exist
  14696. */
  14697. Engine.prototype.removeExternalData = function (key) {
  14698. if (!this._externalData) {
  14699. this._externalData = new BABYLON.StringDictionary();
  14700. }
  14701. return this._externalData.remove(key);
  14702. };
  14703. Engine.prototype.unbindAllAttributes = function () {
  14704. if (this._mustWipeVertexAttributes) {
  14705. this._mustWipeVertexAttributes = false;
  14706. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14707. this._gl.disableVertexAttribArray(i);
  14708. this._vertexAttribArraysEnabled[i] = false;
  14709. this._currentBufferPointers[i].active = false;
  14710. }
  14711. return;
  14712. }
  14713. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14714. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14715. continue;
  14716. }
  14717. this._gl.disableVertexAttribArray(i);
  14718. this._vertexAttribArraysEnabled[i] = false;
  14719. this._currentBufferPointers[i].active = false;
  14720. }
  14721. };
  14722. Engine.prototype.releaseEffects = function () {
  14723. for (var name in this._compiledEffects) {
  14724. this._deleteProgram(this._compiledEffects[name]._program);
  14725. }
  14726. this._compiledEffects = {};
  14727. };
  14728. // Dispose
  14729. Engine.prototype.dispose = function () {
  14730. this.hideLoadingUI();
  14731. this.stopRenderLoop();
  14732. // Release postProcesses
  14733. while (this.postProcesses.length) {
  14734. this.postProcesses[0].dispose();
  14735. }
  14736. // Empty texture
  14737. if (this._emptyTexture) {
  14738. this._releaseTexture(this._emptyTexture);
  14739. this._emptyTexture = null;
  14740. }
  14741. if (this._emptyCubeTexture) {
  14742. this._releaseTexture(this._emptyCubeTexture);
  14743. this._emptyCubeTexture = null;
  14744. }
  14745. // Rescale PP
  14746. if (this._rescalePostProcess) {
  14747. this._rescalePostProcess.dispose();
  14748. }
  14749. // Release scenes
  14750. while (this.scenes.length) {
  14751. this.scenes[0].dispose();
  14752. }
  14753. // Release audio engine
  14754. if (Engine.audioEngine) {
  14755. Engine.audioEngine.dispose();
  14756. }
  14757. // Release effects
  14758. this.releaseEffects();
  14759. // Unbind
  14760. this.unbindAllAttributes();
  14761. if (this._dummyFramebuffer) {
  14762. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14763. }
  14764. //WebVR
  14765. this.disableVR();
  14766. // Events
  14767. if (BABYLON.Tools.IsWindowObjectExist()) {
  14768. window.removeEventListener("blur", this._onBlur);
  14769. window.removeEventListener("focus", this._onFocus);
  14770. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14771. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14772. if (this._renderingCanvas) {
  14773. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14774. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14775. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14776. if (!this._doNotHandleContextLost) {
  14777. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14778. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14779. }
  14780. }
  14781. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14782. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14783. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14784. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14785. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14786. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14787. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14788. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14789. if (this._onVrDisplayConnect) {
  14790. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14791. if (this._onVrDisplayDisconnect) {
  14792. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14793. }
  14794. if (this._onVrDisplayPresentChange) {
  14795. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14796. }
  14797. this._onVrDisplayConnect = null;
  14798. this._onVrDisplayDisconnect = null;
  14799. }
  14800. }
  14801. // Remove from Instances
  14802. var index = Engine.Instances.indexOf(this);
  14803. if (index >= 0) {
  14804. Engine.Instances.splice(index, 1);
  14805. }
  14806. this._workingCanvas = null;
  14807. this._workingContext = null;
  14808. this._currentBufferPointers = [];
  14809. this._renderingCanvas = null;
  14810. this._currentProgram = null;
  14811. this.onResizeObservable.clear();
  14812. this.onCanvasBlurObservable.clear();
  14813. this.onCanvasFocusObservable.clear();
  14814. this.onCanvasPointerOutObservable.clear();
  14815. this.onBeginFrameObservable.clear();
  14816. this.onEndFrameObservable.clear();
  14817. BABYLON.Effect.ResetCache();
  14818. // Abort active requests
  14819. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14820. var request = _a[_i];
  14821. request.abort();
  14822. }
  14823. };
  14824. // Loading screen
  14825. Engine.prototype.displayLoadingUI = function () {
  14826. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14827. return;
  14828. }
  14829. var loadingScreen = this.loadingScreen;
  14830. if (loadingScreen) {
  14831. loadingScreen.displayLoadingUI();
  14832. }
  14833. };
  14834. Engine.prototype.hideLoadingUI = function () {
  14835. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14836. return;
  14837. }
  14838. var loadingScreen = this.loadingScreen;
  14839. if (loadingScreen) {
  14840. loadingScreen.hideLoadingUI();
  14841. }
  14842. };
  14843. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14844. get: function () {
  14845. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14846. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14847. return this._loadingScreen;
  14848. },
  14849. set: function (loadingScreen) {
  14850. this._loadingScreen = loadingScreen;
  14851. },
  14852. enumerable: true,
  14853. configurable: true
  14854. });
  14855. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14856. set: function (text) {
  14857. this.loadingScreen.loadingUIText = text;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14863. set: function (color) {
  14864. this.loadingScreen.loadingUIBackgroundColor = color;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. Engine.prototype.attachContextLostEvent = function (callback) {
  14870. if (this._renderingCanvas) {
  14871. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14872. }
  14873. };
  14874. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14875. if (this._renderingCanvas) {
  14876. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14877. }
  14878. };
  14879. Engine.prototype.getVertexShaderSource = function (program) {
  14880. var shaders = this._gl.getAttachedShaders(program);
  14881. if (!shaders) {
  14882. return null;
  14883. }
  14884. return this._gl.getShaderSource(shaders[0]);
  14885. };
  14886. Engine.prototype.getFragmentShaderSource = function (program) {
  14887. var shaders = this._gl.getAttachedShaders(program);
  14888. if (!shaders) {
  14889. return null;
  14890. }
  14891. return this._gl.getShaderSource(shaders[1]);
  14892. };
  14893. Engine.prototype.getError = function () {
  14894. return this._gl.getError();
  14895. };
  14896. // FPS
  14897. Engine.prototype.getFps = function () {
  14898. return this._fps;
  14899. };
  14900. Engine.prototype.getDeltaTime = function () {
  14901. return this._deltaTime;
  14902. };
  14903. Engine.prototype._measureFps = function () {
  14904. this._performanceMonitor.sampleFrame();
  14905. this._fps = this._performanceMonitor.averageFPS;
  14906. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14907. };
  14908. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14909. if (faceIndex === void 0) { faceIndex = -1; }
  14910. var gl = this._gl;
  14911. if (!this._dummyFramebuffer) {
  14912. var dummy = gl.createFramebuffer();
  14913. if (!dummy) {
  14914. throw new Error("Unable to create dummy framebuffer");
  14915. }
  14916. this._dummyFramebuffer = dummy;
  14917. }
  14918. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14919. if (faceIndex > -1) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14924. }
  14925. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14926. var buffer;
  14927. switch (readType) {
  14928. case gl.UNSIGNED_BYTE:
  14929. buffer = new Uint8Array(4 * width * height);
  14930. readType = gl.UNSIGNED_BYTE;
  14931. break;
  14932. default:
  14933. buffer = new Float32Array(4 * width * height);
  14934. readType = gl.FLOAT;
  14935. break;
  14936. }
  14937. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14938. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14939. return buffer;
  14940. };
  14941. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14942. if (this._webGLVersion > 1) {
  14943. return this._caps.colorBufferFloat;
  14944. }
  14945. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14946. };
  14947. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14948. if (this._webGLVersion > 1) {
  14949. return this._caps.colorBufferFloat;
  14950. }
  14951. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14952. };
  14953. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14954. Engine.prototype._canRenderToFramebuffer = function (type) {
  14955. var gl = this._gl;
  14956. //clear existing errors
  14957. while (gl.getError() !== gl.NO_ERROR) { }
  14958. var successful = true;
  14959. var texture = gl.createTexture();
  14960. gl.bindTexture(gl.TEXTURE_2D, texture);
  14961. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14964. var fb = gl.createFramebuffer();
  14965. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14966. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14967. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14968. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14969. successful = successful && (gl.getError() === gl.NO_ERROR);
  14970. //try render by clearing frame buffer's color buffer
  14971. if (successful) {
  14972. gl.clear(gl.COLOR_BUFFER_BIT);
  14973. successful = successful && (gl.getError() === gl.NO_ERROR);
  14974. }
  14975. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14976. if (successful) {
  14977. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14978. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14979. var readFormat = gl.RGBA;
  14980. var readType = gl.UNSIGNED_BYTE;
  14981. var buffer = new Uint8Array(4);
  14982. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14983. successful = successful && (gl.getError() === gl.NO_ERROR);
  14984. }
  14985. //clean up
  14986. gl.deleteTexture(texture);
  14987. gl.deleteFramebuffer(fb);
  14988. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14989. //clear accumulated errors
  14990. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14991. return successful;
  14992. };
  14993. Engine.prototype._getWebGLTextureType = function (type) {
  14994. if (type === Engine.TEXTURETYPE_FLOAT) {
  14995. return this._gl.FLOAT;
  14996. }
  14997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14998. // Add Half Float Constant.
  14999. return this._gl.HALF_FLOAT_OES;
  15000. }
  15001. return this._gl.UNSIGNED_BYTE;
  15002. };
  15003. ;
  15004. /** @ignore */
  15005. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15006. if (this._webGLVersion === 1) {
  15007. return this._gl.RGBA;
  15008. }
  15009. if (type === Engine.TEXTURETYPE_FLOAT) {
  15010. if (format) {
  15011. switch (format) {
  15012. case Engine.TEXTUREFORMAT_R32F:
  15013. return this._gl.R32F;
  15014. case Engine.TEXTUREFORMAT_RG32F:
  15015. return this._gl.RG32F;
  15016. case Engine.TEXTUREFORMAT_RGB32F:
  15017. return this._gl.RGB32F;
  15018. }
  15019. }
  15020. return this._gl.RGBA32F;
  15021. }
  15022. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15023. return this._gl.RGBA16F;
  15024. }
  15025. return this._gl.RGBA;
  15026. };
  15027. ;
  15028. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15029. if (type === Engine.TEXTURETYPE_FLOAT) {
  15030. return this._gl.RGBA32F;
  15031. }
  15032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15033. return this._gl.RGBA16F;
  15034. }
  15035. return this._gl.RGBA8;
  15036. };
  15037. ;
  15038. Engine.prototype.createQuery = function () {
  15039. return this._gl.createQuery();
  15040. };
  15041. Engine.prototype.deleteQuery = function (query) {
  15042. this._gl.deleteQuery(query);
  15043. return this;
  15044. };
  15045. Engine.prototype.isQueryResultAvailable = function (query) {
  15046. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15047. };
  15048. Engine.prototype.getQueryResult = function (query) {
  15049. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15050. };
  15051. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15052. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15053. this._gl.beginQuery(glAlgorithm, query);
  15054. return this;
  15055. };
  15056. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15057. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15058. this._gl.endQuery(glAlgorithm);
  15059. return this;
  15060. };
  15061. /* Time queries */
  15062. Engine.prototype._createTimeQuery = function () {
  15063. var timerQuery = this._caps.timerQuery;
  15064. if (timerQuery.createQueryEXT) {
  15065. return timerQuery.createQueryEXT();
  15066. }
  15067. return this.createQuery();
  15068. };
  15069. Engine.prototype._deleteTimeQuery = function (query) {
  15070. var timerQuery = this._caps.timerQuery;
  15071. if (timerQuery.deleteQueryEXT) {
  15072. timerQuery.deleteQueryEXT(query);
  15073. return;
  15074. }
  15075. this.deleteQuery(query);
  15076. };
  15077. Engine.prototype._getTimeQueryResult = function (query) {
  15078. var timerQuery = this._caps.timerQuery;
  15079. if (timerQuery.getQueryObjectEXT) {
  15080. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15081. }
  15082. return this.getQueryResult(query);
  15083. };
  15084. Engine.prototype._getTimeQueryAvailability = function (query) {
  15085. var timerQuery = this._caps.timerQuery;
  15086. if (timerQuery.getQueryObjectEXT) {
  15087. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15088. }
  15089. return this.isQueryResultAvailable(query);
  15090. };
  15091. Engine.prototype.startTimeQuery = function () {
  15092. var timerQuery = this._caps.timerQuery;
  15093. if (!timerQuery) {
  15094. return null;
  15095. }
  15096. var token = new BABYLON._TimeToken();
  15097. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15098. if (this._caps.canUseTimestampForTimerQuery) {
  15099. token._startTimeQuery = this._createTimeQuery();
  15100. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15101. }
  15102. else {
  15103. if (this._currentNonTimestampToken) {
  15104. return this._currentNonTimestampToken;
  15105. }
  15106. token._timeElapsedQuery = this._createTimeQuery();
  15107. if (timerQuery.beginQueryEXT) {
  15108. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15109. }
  15110. else {
  15111. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15112. }
  15113. this._currentNonTimestampToken = token;
  15114. }
  15115. return token;
  15116. };
  15117. Engine.prototype.endTimeQuery = function (token) {
  15118. var timerQuery = this._caps.timerQuery;
  15119. if (!timerQuery || !token) {
  15120. return -1;
  15121. }
  15122. if (this._caps.canUseTimestampForTimerQuery) {
  15123. if (!token._startTimeQuery) {
  15124. return -1;
  15125. }
  15126. if (!token._endTimeQuery) {
  15127. token._endTimeQuery = this._createTimeQuery();
  15128. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15129. }
  15130. }
  15131. else if (!token._timeElapsedQueryEnded) {
  15132. if (!token._timeElapsedQuery) {
  15133. return -1;
  15134. }
  15135. if (timerQuery.endQueryEXT) {
  15136. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15137. }
  15138. else {
  15139. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15140. }
  15141. token._timeElapsedQueryEnded = true;
  15142. }
  15143. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15144. var available = false;
  15145. if (token._endTimeQuery) {
  15146. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15147. }
  15148. else if (token._timeElapsedQuery) {
  15149. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15150. }
  15151. if (available && !disjoint) {
  15152. var result = 0;
  15153. if (this._caps.canUseTimestampForTimerQuery) {
  15154. if (!token._startTimeQuery || !token._endTimeQuery) {
  15155. return -1;
  15156. }
  15157. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15158. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15159. result = timeEnd - timeStart;
  15160. this._deleteTimeQuery(token._startTimeQuery);
  15161. this._deleteTimeQuery(token._endTimeQuery);
  15162. token._startTimeQuery = null;
  15163. token._endTimeQuery = null;
  15164. }
  15165. else {
  15166. if (!token._timeElapsedQuery) {
  15167. return -1;
  15168. }
  15169. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15170. this._deleteTimeQuery(token._timeElapsedQuery);
  15171. token._timeElapsedQuery = null;
  15172. token._timeElapsedQueryEnded = false;
  15173. this._currentNonTimestampToken = null;
  15174. }
  15175. return result;
  15176. }
  15177. return -1;
  15178. };
  15179. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15180. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15181. };
  15182. // Transform feedback
  15183. Engine.prototype.createTransformFeedback = function () {
  15184. return this._gl.createTransformFeedback();
  15185. };
  15186. Engine.prototype.deleteTransformFeedback = function (value) {
  15187. this._gl.deleteTransformFeedback(value);
  15188. };
  15189. Engine.prototype.bindTransformFeedback = function (value) {
  15190. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15191. };
  15192. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15193. if (usePoints === void 0) { usePoints = true; }
  15194. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15195. };
  15196. Engine.prototype.endTransformFeedback = function () {
  15197. this._gl.endTransformFeedback();
  15198. };
  15199. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15200. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15201. };
  15202. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15203. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15204. };
  15205. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15206. var _this = this;
  15207. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15208. this._activeRequests.push(request);
  15209. request.onCompleteObservable.add(function (request) {
  15210. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15211. });
  15212. return request;
  15213. };
  15214. /** @ignore */
  15215. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15216. var _this = this;
  15217. return new Promise(function (resolve, reject) {
  15218. _this._loadFile(url, function (data) {
  15219. resolve(data);
  15220. }, undefined, database, useArrayBuffer, function (request, exception) {
  15221. reject(exception);
  15222. });
  15223. });
  15224. };
  15225. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15226. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15227. var onload = function (data) {
  15228. loadedFiles[index] = data;
  15229. loadedFiles._internalCount++;
  15230. if (loadedFiles._internalCount === 6) {
  15231. onfinish(loadedFiles);
  15232. }
  15233. };
  15234. var onerror = function (request, exception) {
  15235. if (onErrorCallBack && request) {
  15236. onErrorCallBack(request.status + " " + request.statusText, exception);
  15237. }
  15238. };
  15239. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15240. };
  15241. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15242. if (onError === void 0) { onError = null; }
  15243. var loadedFiles = [];
  15244. loadedFiles._internalCount = 0;
  15245. for (var index = 0; index < 6; index++) {
  15246. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15247. }
  15248. };
  15249. // Statics
  15250. Engine.isSupported = function () {
  15251. try {
  15252. var tempcanvas = document.createElement("canvas");
  15253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15254. return gl != null && !!window.WebGLRenderingContext;
  15255. }
  15256. catch (e) {
  15257. return false;
  15258. }
  15259. };
  15260. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15261. Engine.ExceptionList = [
  15262. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15263. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15264. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15265. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15266. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15267. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15268. ];
  15269. Engine.Instances = new Array();
  15270. // Const statics
  15271. Engine._ALPHA_DISABLE = 0;
  15272. Engine._ALPHA_ADD = 1;
  15273. Engine._ALPHA_COMBINE = 2;
  15274. Engine._ALPHA_SUBTRACT = 3;
  15275. Engine._ALPHA_MULTIPLY = 4;
  15276. Engine._ALPHA_MAXIMIZED = 5;
  15277. Engine._ALPHA_ONEONE = 6;
  15278. Engine._ALPHA_PREMULTIPLIED = 7;
  15279. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15280. Engine._ALPHA_INTERPOLATE = 9;
  15281. Engine._ALPHA_SCREENMODE = 10;
  15282. Engine._DELAYLOADSTATE_NONE = 0;
  15283. Engine._DELAYLOADSTATE_LOADED = 1;
  15284. Engine._DELAYLOADSTATE_LOADING = 2;
  15285. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15286. Engine._TEXTUREFORMAT_ALPHA = 0;
  15287. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15288. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15289. Engine._TEXTUREFORMAT_RGB = 4;
  15290. Engine._TEXTUREFORMAT_RGBA = 5;
  15291. Engine._TEXTUREFORMAT_R32F = 6;
  15292. Engine._TEXTUREFORMAT_RG32F = 7;
  15293. Engine._TEXTUREFORMAT_RGB32F = 8;
  15294. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15295. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15296. Engine._TEXTURETYPE_FLOAT = 1;
  15297. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15298. // Depht or Stencil test Constants.
  15299. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15300. 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.
  15301. 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.
  15302. 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.
  15303. 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.
  15304. 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.
  15305. 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.
  15306. 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.
  15307. // Stencil Actions Constants.
  15308. Engine._KEEP = 0x1E00;
  15309. Engine._REPLACE = 0x1E01;
  15310. Engine._INCR = 0x1E02;
  15311. Engine._DECR = 0x1E03;
  15312. Engine._INVERT = 0x150A;
  15313. Engine._INCR_WRAP = 0x8507;
  15314. Engine._DECR_WRAP = 0x8508;
  15315. // Texture rescaling mode
  15316. Engine._SCALEMODE_FLOOR = 1;
  15317. Engine._SCALEMODE_NEAREST = 2;
  15318. Engine._SCALEMODE_CEILING = 3;
  15319. // Updatable statics so stick with vars here
  15320. Engine.CollisionsEpsilon = 0.001;
  15321. Engine.CodeRepository = "src/";
  15322. Engine.ShadersRepository = "src/Shaders/";
  15323. return Engine;
  15324. }());
  15325. BABYLON.Engine = Engine;
  15326. })(BABYLON || (BABYLON = {}));
  15327. //# sourceMappingURL=babylon.engine.js.map
  15328. var BABYLON;
  15329. (function (BABYLON) {
  15330. /**
  15331. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15332. */
  15333. var Node = /** @class */ (function () {
  15334. /**
  15335. * Creates a new Node
  15336. * @param {string} name - the name and id to be given to this node
  15337. * @param {BABYLON.Scene} the scene this node will be added to
  15338. */
  15339. function Node(name, scene) {
  15340. if (scene === void 0) { scene = null; }
  15341. /**
  15342. * Gets or sets a string used to store user defined state for the node
  15343. */
  15344. this.state = "";
  15345. /**
  15346. * Gets or sets an object used to store user defined information for the node
  15347. */
  15348. this.metadata = null;
  15349. /**
  15350. * Gets or sets a boolean used to define if the node must be serialized
  15351. */
  15352. this.doNotSerialize = false;
  15353. /** @ignore */
  15354. this._isDisposed = false;
  15355. /**
  15356. * Gets a list of {BABYLON.Animation} associated with the node
  15357. */
  15358. this.animations = new Array();
  15359. this._ranges = {};
  15360. this._isEnabled = true;
  15361. this._isReady = true;
  15362. /** @ignore */
  15363. this._currentRenderId = -1;
  15364. this._parentRenderId = -1;
  15365. this._animationPropertiesOverride = null;
  15366. /**
  15367. * An event triggered when the mesh is disposed
  15368. * @type {BABYLON.Observable}
  15369. */
  15370. this.onDisposeObservable = new BABYLON.Observable();
  15371. // Behaviors
  15372. this._behaviors = new Array();
  15373. this.name = name;
  15374. this.id = name;
  15375. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15376. this.uniqueId = this._scene.getUniqueId();
  15377. this._initCache();
  15378. }
  15379. /**
  15380. * Gets a boolean indicating if the node has been disposed
  15381. * @returns true if the node was disposed
  15382. */
  15383. Node.prototype.isDisposed = function () {
  15384. return this._isDisposed;
  15385. };
  15386. Object.defineProperty(Node.prototype, "parent", {
  15387. get: function () {
  15388. return this._parentNode;
  15389. },
  15390. /**
  15391. * Gets or sets the parent of the node
  15392. */
  15393. set: function (parent) {
  15394. if (this._parentNode === parent) {
  15395. return;
  15396. }
  15397. // Remove self from list of children of parent
  15398. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15399. var index = this._parentNode._children.indexOf(this);
  15400. if (index !== -1) {
  15401. this._parentNode._children.splice(index, 1);
  15402. }
  15403. }
  15404. // Store new parent
  15405. this._parentNode = parent;
  15406. // Add as child to new parent
  15407. if (this._parentNode) {
  15408. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15409. this._parentNode._children = new Array();
  15410. }
  15411. this._parentNode._children.push(this);
  15412. }
  15413. },
  15414. enumerable: true,
  15415. configurable: true
  15416. });
  15417. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15418. /**
  15419. * Gets or sets the animation properties override
  15420. */
  15421. get: function () {
  15422. return this._animationPropertiesOverride;
  15423. },
  15424. set: function (value) {
  15425. this._animationPropertiesOverride = value;
  15426. },
  15427. enumerable: true,
  15428. configurable: true
  15429. });
  15430. /**
  15431. * Gets a string idenfifying the name of the class
  15432. * @returns "Node" string
  15433. */
  15434. Node.prototype.getClassName = function () {
  15435. return "Node";
  15436. };
  15437. Object.defineProperty(Node.prototype, "onDispose", {
  15438. /**
  15439. * Sets a callback that will be raised when the node will be disposed
  15440. */
  15441. set: function (callback) {
  15442. if (this._onDisposeObserver) {
  15443. this.onDisposeObservable.remove(this._onDisposeObserver);
  15444. }
  15445. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15446. },
  15447. enumerable: true,
  15448. configurable: true
  15449. });
  15450. /**
  15451. * Gets the scene of the node
  15452. * @returns a {BABYLON.Scene}
  15453. */
  15454. Node.prototype.getScene = function () {
  15455. return this._scene;
  15456. };
  15457. /**
  15458. * Gets the engine of the node
  15459. * @returns a {BABYLON.Engine}
  15460. */
  15461. Node.prototype.getEngine = function () {
  15462. return this._scene.getEngine();
  15463. };
  15464. /**
  15465. * Attach a behavior to the node
  15466. * @see http://doc.babylonjs.com/features/behaviour
  15467. * @param behavior defines the behavior to attach
  15468. * @returns the current Node
  15469. */
  15470. Node.prototype.addBehavior = function (behavior) {
  15471. var _this = this;
  15472. var index = this._behaviors.indexOf(behavior);
  15473. if (index !== -1) {
  15474. return this;
  15475. }
  15476. behavior.init();
  15477. if (this._scene.isLoading) {
  15478. // We defer the attach when the scene will be loaded
  15479. var observer = this._scene.onDataLoadedObservable.add(function () {
  15480. behavior.attach(_this);
  15481. setTimeout(function () {
  15482. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15483. _this._scene.onDataLoadedObservable.remove(observer);
  15484. }, 0);
  15485. });
  15486. }
  15487. else {
  15488. behavior.attach(this);
  15489. }
  15490. this._behaviors.push(behavior);
  15491. return this;
  15492. };
  15493. /**
  15494. * Remove an attached behavior
  15495. * @see http://doc.babylonjs.com/features/behaviour
  15496. * @param behavior defines the behavior to attach
  15497. * @returns the current Node
  15498. */
  15499. Node.prototype.removeBehavior = function (behavior) {
  15500. var index = this._behaviors.indexOf(behavior);
  15501. if (index === -1) {
  15502. return this;
  15503. }
  15504. this._behaviors[index].detach();
  15505. this._behaviors.splice(index, 1);
  15506. return this;
  15507. };
  15508. Object.defineProperty(Node.prototype, "behaviors", {
  15509. /**
  15510. * Gets the list of attached behaviors
  15511. * @see http://doc.babylonjs.com/features/behaviour
  15512. */
  15513. get: function () {
  15514. return this._behaviors;
  15515. },
  15516. enumerable: true,
  15517. configurable: true
  15518. });
  15519. /**
  15520. * Gets an attached behavior by name
  15521. * @param name defines the name of the behavior to look for
  15522. * @see http://doc.babylonjs.com/features/behaviour
  15523. * @returns null if behavior was not found else the requested behavior
  15524. */
  15525. Node.prototype.getBehaviorByName = function (name) {
  15526. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15527. var behavior = _a[_i];
  15528. if (behavior.name === name) {
  15529. return behavior;
  15530. }
  15531. }
  15532. return null;
  15533. };
  15534. /**
  15535. * Returns the world matrix of the node
  15536. * @returns a matrix containing the node's world matrix
  15537. */
  15538. Node.prototype.getWorldMatrix = function () {
  15539. return BABYLON.Matrix.Identity();
  15540. };
  15541. // override it in derived class if you add new variables to the cache
  15542. // and call the parent class method
  15543. /** @ignore */
  15544. Node.prototype._initCache = function () {
  15545. this._cache = {};
  15546. this._cache.parent = undefined;
  15547. };
  15548. /** @ignore */
  15549. Node.prototype.updateCache = function (force) {
  15550. if (!force && this.isSynchronized())
  15551. return;
  15552. this._cache.parent = this.parent;
  15553. this._updateCache();
  15554. };
  15555. // override it in derived class if you add new variables to the cache
  15556. // and call the parent class method if !ignoreParentClass
  15557. /** @ignore */
  15558. Node.prototype._updateCache = function (ignoreParentClass) {
  15559. };
  15560. // override it in derived class if you add new variables to the cache
  15561. /** @ignore */
  15562. Node.prototype._isSynchronized = function () {
  15563. return true;
  15564. };
  15565. /** @ignore */
  15566. Node.prototype._markSyncedWithParent = function () {
  15567. if (this.parent) {
  15568. this._parentRenderId = this.parent._currentRenderId;
  15569. }
  15570. };
  15571. /** @ignore */
  15572. Node.prototype.isSynchronizedWithParent = function () {
  15573. if (!this.parent) {
  15574. return true;
  15575. }
  15576. if (this._parentRenderId !== this.parent._currentRenderId) {
  15577. return false;
  15578. }
  15579. return this.parent.isSynchronized();
  15580. };
  15581. /** @ignore */
  15582. Node.prototype.isSynchronized = function (updateCache) {
  15583. var check = this.hasNewParent();
  15584. check = check || !this.isSynchronizedWithParent();
  15585. check = check || !this._isSynchronized();
  15586. if (updateCache)
  15587. this.updateCache(true);
  15588. return !check;
  15589. };
  15590. /** @ignore */
  15591. Node.prototype.hasNewParent = function (update) {
  15592. if (this._cache.parent === this.parent)
  15593. return false;
  15594. if (update)
  15595. this._cache.parent = this.parent;
  15596. return true;
  15597. };
  15598. /**
  15599. * Is this node ready to be used/rendered
  15600. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15601. * @return true if the node is ready
  15602. */
  15603. Node.prototype.isReady = function (completeCheck) {
  15604. if (completeCheck === void 0) { completeCheck = false; }
  15605. return this._isReady;
  15606. };
  15607. /**
  15608. * Is this node enabled?
  15609. * 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
  15610. * @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
  15611. * @return whether this node (and its parent) is enabled
  15612. * @see setEnabled
  15613. */
  15614. Node.prototype.isEnabled = function (checkAncestors) {
  15615. if (checkAncestors === void 0) { checkAncestors = true; }
  15616. if (checkAncestors === false) {
  15617. return this._isEnabled;
  15618. }
  15619. if (this._isEnabled === false) {
  15620. return false;
  15621. }
  15622. if (this.parent !== undefined && this.parent !== null) {
  15623. return this.parent.isEnabled(checkAncestors);
  15624. }
  15625. return true;
  15626. };
  15627. /**
  15628. * Set the enabled state of this node
  15629. * @param value defines the new enabled state
  15630. * @see isEnabled
  15631. */
  15632. Node.prototype.setEnabled = function (value) {
  15633. this._isEnabled = value;
  15634. };
  15635. /**
  15636. * Is this node a descendant of the given node?
  15637. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15638. * @param ancestor defines the parent node to inspect
  15639. * @see parent
  15640. * @returns a boolean indicating if this node is a descendant of the given node
  15641. */
  15642. Node.prototype.isDescendantOf = function (ancestor) {
  15643. if (this.parent) {
  15644. if (this.parent === ancestor) {
  15645. return true;
  15646. }
  15647. return this.parent.isDescendantOf(ancestor);
  15648. }
  15649. return false;
  15650. };
  15651. /** @ignore */
  15652. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15653. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15654. if (!this._children) {
  15655. return;
  15656. }
  15657. for (var index = 0; index < this._children.length; index++) {
  15658. var item = this._children[index];
  15659. if (!predicate || predicate(item)) {
  15660. results.push(item);
  15661. }
  15662. if (!directDescendantsOnly) {
  15663. item._getDescendants(results, false, predicate);
  15664. }
  15665. }
  15666. };
  15667. /**
  15668. * Will return all nodes that have this node as ascendant
  15669. * @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
  15670. * @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
  15671. * @return all children nodes of all types
  15672. */
  15673. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15674. var results = new Array();
  15675. this._getDescendants(results, directDescendantsOnly, predicate);
  15676. return results;
  15677. };
  15678. /**
  15679. * Get all child-meshes of this node
  15680. * @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
  15681. * @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
  15682. * @returns an array of {BABYLON.AbstractMesh}
  15683. */
  15684. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15685. var results = [];
  15686. this._getDescendants(results, directDescendantsOnly, function (node) {
  15687. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15688. });
  15689. return results;
  15690. };
  15691. /**
  15692. * Get all child-transformNodes of this node
  15693. * @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
  15694. * @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
  15695. * @returns an array of {BABYLON.TransformNode}
  15696. */
  15697. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15698. var results = [];
  15699. this._getDescendants(results, directDescendantsOnly, function (node) {
  15700. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15701. });
  15702. return results;
  15703. };
  15704. /**
  15705. * Get all direct children of this node
  15706. * @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
  15707. * @returns an array of {BABYLON.Node}
  15708. */
  15709. Node.prototype.getChildren = function (predicate) {
  15710. return this.getDescendants(true, predicate);
  15711. };
  15712. /** @ignore */
  15713. Node.prototype._setReady = function (state) {
  15714. if (state === this._isReady) {
  15715. return;
  15716. }
  15717. if (!state) {
  15718. this._isReady = false;
  15719. return;
  15720. }
  15721. this._isReady = true;
  15722. if (this.onReady) {
  15723. this.onReady(this);
  15724. }
  15725. };
  15726. /**
  15727. * Get an animation by name
  15728. * @param name defines the name of the animation to look for
  15729. * @returns null if not found else the requested animation
  15730. */
  15731. Node.prototype.getAnimationByName = function (name) {
  15732. for (var i = 0; i < this.animations.length; i++) {
  15733. var animation = this.animations[i];
  15734. if (animation.name === name) {
  15735. return animation;
  15736. }
  15737. }
  15738. return null;
  15739. };
  15740. /**
  15741. * Creates an animation range for this node
  15742. * @param name defines the name of the range
  15743. * @param from defines the starting key
  15744. * @param to defines the end key
  15745. */
  15746. Node.prototype.createAnimationRange = function (name, from, to) {
  15747. // check name not already in use
  15748. if (!this._ranges[name]) {
  15749. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15750. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15751. if (this.animations[i]) {
  15752. this.animations[i].createRange(name, from, to);
  15753. }
  15754. }
  15755. }
  15756. };
  15757. /**
  15758. * Delete a specific animation range
  15759. * @param name defines the name of the range to delete
  15760. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15761. */
  15762. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15763. if (deleteFrames === void 0) { deleteFrames = true; }
  15764. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15765. if (this.animations[i]) {
  15766. this.animations[i].deleteRange(name, deleteFrames);
  15767. }
  15768. }
  15769. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15770. };
  15771. /**
  15772. * Get an animation range by name
  15773. * @param name defines the name of the animation range to look for
  15774. * @returns null if not found else the requested animation range
  15775. */
  15776. Node.prototype.getAnimationRange = function (name) {
  15777. return this._ranges[name];
  15778. };
  15779. /**
  15780. * Will start the animation sequence
  15781. * @param name defines the range frames for animation sequence
  15782. * @param loop defines if the animation should loop (false by default)
  15783. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15784. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15785. * @returns the object created for this animation. If range does not exist, it will return null
  15786. */
  15787. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15788. var range = this.getAnimationRange(name);
  15789. if (!range) {
  15790. return null;
  15791. }
  15792. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15793. };
  15794. /**
  15795. * Serialize animation ranges into a JSON compatible object
  15796. * @returns serialization object
  15797. */
  15798. Node.prototype.serializeAnimationRanges = function () {
  15799. var serializationRanges = [];
  15800. for (var name in this._ranges) {
  15801. var localRange = this._ranges[name];
  15802. if (!localRange) {
  15803. continue;
  15804. }
  15805. var range = {};
  15806. range.name = name;
  15807. range.from = localRange.from;
  15808. range.to = localRange.to;
  15809. serializationRanges.push(range);
  15810. }
  15811. return serializationRanges;
  15812. };
  15813. /**
  15814. * Computes the world matrix of the node
  15815. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15816. * @returns the world matrix
  15817. */
  15818. Node.prototype.computeWorldMatrix = function (force) {
  15819. return BABYLON.Matrix.Identity();
  15820. };
  15821. /**
  15822. * Releases all associated resources
  15823. */
  15824. Node.prototype.dispose = function () {
  15825. this.parent = null;
  15826. // Callback
  15827. this.onDisposeObservable.notifyObservers(this);
  15828. this.onDisposeObservable.clear();
  15829. // Behaviors
  15830. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15831. var behavior = _a[_i];
  15832. behavior.detach();
  15833. }
  15834. this._behaviors = [];
  15835. this._isDisposed = true;
  15836. };
  15837. /**
  15838. * Parse animation range data from a serialization object and store them into a given node
  15839. * @param node defines where to store the animation ranges
  15840. * @param parsedNode defines the serialization object to read data from
  15841. * @param scene defines the hosting scene
  15842. */
  15843. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15844. if (parsedNode.ranges) {
  15845. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15846. var data = parsedNode.ranges[index];
  15847. node.createAnimationRange(data.name, data.from, data.to);
  15848. }
  15849. }
  15850. };
  15851. __decorate([
  15852. BABYLON.serialize()
  15853. ], Node.prototype, "name", void 0);
  15854. __decorate([
  15855. BABYLON.serialize()
  15856. ], Node.prototype, "id", void 0);
  15857. __decorate([
  15858. BABYLON.serialize()
  15859. ], Node.prototype, "uniqueId", void 0);
  15860. __decorate([
  15861. BABYLON.serialize()
  15862. ], Node.prototype, "state", void 0);
  15863. __decorate([
  15864. BABYLON.serialize()
  15865. ], Node.prototype, "metadata", void 0);
  15866. return Node;
  15867. }());
  15868. BABYLON.Node = Node;
  15869. })(BABYLON || (BABYLON = {}));
  15870. //# sourceMappingURL=babylon.node.js.map
  15871. var BABYLON;
  15872. (function (BABYLON) {
  15873. var BoundingSphere = /** @class */ (function () {
  15874. function BoundingSphere(minimum, maximum) {
  15875. this.minimum = minimum;
  15876. this.maximum = maximum;
  15877. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15878. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15879. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15880. this.radius = distance * 0.5;
  15881. this.centerWorld = BABYLON.Vector3.Zero();
  15882. this._update(BABYLON.Matrix.Identity());
  15883. }
  15884. // Methods
  15885. BoundingSphere.prototype._update = function (world) {
  15886. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15887. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15888. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15889. };
  15890. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15891. for (var i = 0; i < 6; i++) {
  15892. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15893. return false;
  15894. }
  15895. return true;
  15896. };
  15897. BoundingSphere.prototype.intersectsPoint = function (point) {
  15898. var x = this.centerWorld.x - point.x;
  15899. var y = this.centerWorld.y - point.y;
  15900. var z = this.centerWorld.z - point.z;
  15901. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15902. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15903. return false;
  15904. return true;
  15905. };
  15906. // Statics
  15907. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15908. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15909. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15910. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15911. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15912. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15913. return false;
  15914. return true;
  15915. };
  15916. return BoundingSphere;
  15917. }());
  15918. BABYLON.BoundingSphere = BoundingSphere;
  15919. })(BABYLON || (BABYLON = {}));
  15920. //# sourceMappingURL=babylon.boundingSphere.js.map
  15921. var BABYLON;
  15922. (function (BABYLON) {
  15923. var BoundingBox = /** @class */ (function () {
  15924. function BoundingBox(minimum, maximum) {
  15925. this.minimum = minimum;
  15926. this.maximum = maximum;
  15927. this.vectors = new Array();
  15928. this.vectorsWorld = new Array();
  15929. // Bounding vectors
  15930. this.vectors.push(this.minimum.clone());
  15931. this.vectors.push(this.maximum.clone());
  15932. this.vectors.push(this.minimum.clone());
  15933. this.vectors[2].x = this.maximum.x;
  15934. this.vectors.push(this.minimum.clone());
  15935. this.vectors[3].y = this.maximum.y;
  15936. this.vectors.push(this.minimum.clone());
  15937. this.vectors[4].z = this.maximum.z;
  15938. this.vectors.push(this.maximum.clone());
  15939. this.vectors[5].z = this.minimum.z;
  15940. this.vectors.push(this.maximum.clone());
  15941. this.vectors[6].x = this.minimum.x;
  15942. this.vectors.push(this.maximum.clone());
  15943. this.vectors[7].y = this.minimum.y;
  15944. // OBB
  15945. this.center = this.maximum.add(this.minimum).scale(0.5);
  15946. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15947. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15948. // World
  15949. for (var index = 0; index < this.vectors.length; index++) {
  15950. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15951. }
  15952. this.minimumWorld = BABYLON.Vector3.Zero();
  15953. this.maximumWorld = BABYLON.Vector3.Zero();
  15954. this.centerWorld = BABYLON.Vector3.Zero();
  15955. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15956. this._update(BABYLON.Matrix.Identity());
  15957. }
  15958. // Methods
  15959. BoundingBox.prototype.getWorldMatrix = function () {
  15960. return this._worldMatrix;
  15961. };
  15962. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15963. this._worldMatrix.copyFrom(matrix);
  15964. return this;
  15965. };
  15966. BoundingBox.prototype._update = function (world) {
  15967. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15968. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15969. for (var index = 0; index < this.vectors.length; index++) {
  15970. var v = this.vectorsWorld[index];
  15971. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15972. if (v.x < this.minimumWorld.x)
  15973. this.minimumWorld.x = v.x;
  15974. if (v.y < this.minimumWorld.y)
  15975. this.minimumWorld.y = v.y;
  15976. if (v.z < this.minimumWorld.z)
  15977. this.minimumWorld.z = v.z;
  15978. if (v.x > this.maximumWorld.x)
  15979. this.maximumWorld.x = v.x;
  15980. if (v.y > this.maximumWorld.y)
  15981. this.maximumWorld.y = v.y;
  15982. if (v.z > this.maximumWorld.z)
  15983. this.maximumWorld.z = v.z;
  15984. }
  15985. // Extend
  15986. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15987. this.extendSizeWorld.scaleInPlace(0.5);
  15988. // OBB
  15989. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15990. this.centerWorld.scaleInPlace(0.5);
  15991. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15992. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15993. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15994. this._worldMatrix = world;
  15995. };
  15996. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15997. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15998. };
  15999. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16000. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16001. };
  16002. BoundingBox.prototype.intersectsPoint = function (point) {
  16003. var delta = -BABYLON.Epsilon;
  16004. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16005. return false;
  16006. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16007. return false;
  16008. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16009. return false;
  16010. return true;
  16011. };
  16012. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16013. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16014. };
  16015. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16016. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16017. return false;
  16018. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16019. return false;
  16020. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16021. return false;
  16022. return true;
  16023. };
  16024. // Statics
  16025. BoundingBox.Intersects = function (box0, box1) {
  16026. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16027. return false;
  16028. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16029. return false;
  16030. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16031. return false;
  16032. return true;
  16033. };
  16034. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16035. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16036. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16037. return (num <= (sphereRadius * sphereRadius));
  16038. };
  16039. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16040. for (var p = 0; p < 6; p++) {
  16041. for (var i = 0; i < 8; i++) {
  16042. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16043. return false;
  16044. }
  16045. }
  16046. }
  16047. return true;
  16048. };
  16049. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16050. for (var p = 0; p < 6; p++) {
  16051. var inCount = 8;
  16052. for (var i = 0; i < 8; i++) {
  16053. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16054. --inCount;
  16055. }
  16056. else {
  16057. break;
  16058. }
  16059. }
  16060. if (inCount === 0)
  16061. return false;
  16062. }
  16063. return true;
  16064. };
  16065. return BoundingBox;
  16066. }());
  16067. BABYLON.BoundingBox = BoundingBox;
  16068. })(BABYLON || (BABYLON = {}));
  16069. //# sourceMappingURL=babylon.boundingBox.js.map
  16070. var BABYLON;
  16071. (function (BABYLON) {
  16072. var computeBoxExtents = function (axis, box) {
  16073. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16074. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16075. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16076. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16077. var r = r0 + r1 + r2;
  16078. return {
  16079. min: p - r,
  16080. max: p + r
  16081. };
  16082. };
  16083. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16084. var axisOverlap = function (axis, box0, box1) {
  16085. var result0 = computeBoxExtents(axis, box0);
  16086. var result1 = computeBoxExtents(axis, box1);
  16087. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16088. };
  16089. var BoundingInfo = /** @class */ (function () {
  16090. function BoundingInfo(minimum, maximum) {
  16091. this.minimum = minimum;
  16092. this.maximum = maximum;
  16093. this._isLocked = false;
  16094. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16095. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16096. }
  16097. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16098. get: function () {
  16099. return this._isLocked;
  16100. },
  16101. set: function (value) {
  16102. this._isLocked = value;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. // Methods
  16108. BoundingInfo.prototype.update = function (world) {
  16109. if (this._isLocked) {
  16110. return;
  16111. }
  16112. this.boundingBox._update(world);
  16113. this.boundingSphere._update(world);
  16114. };
  16115. /**
  16116. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16117. * @param center New center of the bounding info
  16118. * @param extend New extend of the bounding info
  16119. */
  16120. BoundingInfo.prototype.centerOn = function (center, extend) {
  16121. this.minimum = center.subtract(extend);
  16122. this.maximum = center.add(extend);
  16123. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16124. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16125. return this;
  16126. };
  16127. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16128. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16129. return false;
  16130. return this.boundingBox.isInFrustum(frustumPlanes);
  16131. };
  16132. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16133. /**
  16134. * Gets the world distance between the min and max points of the bounding box
  16135. */
  16136. get: function () {
  16137. var boundingBox = this.boundingBox;
  16138. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16139. return size.length();
  16140. },
  16141. enumerable: true,
  16142. configurable: true
  16143. });
  16144. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16145. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16146. };
  16147. BoundingInfo.prototype._checkCollision = function (collider) {
  16148. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16149. };
  16150. BoundingInfo.prototype.intersectsPoint = function (point) {
  16151. if (!this.boundingSphere.centerWorld) {
  16152. return false;
  16153. }
  16154. if (!this.boundingSphere.intersectsPoint(point)) {
  16155. return false;
  16156. }
  16157. if (!this.boundingBox.intersectsPoint(point)) {
  16158. return false;
  16159. }
  16160. return true;
  16161. };
  16162. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16163. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16164. return false;
  16165. }
  16166. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16167. return false;
  16168. }
  16169. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16170. return false;
  16171. }
  16172. if (!precise) {
  16173. return true;
  16174. }
  16175. var box0 = this.boundingBox;
  16176. var box1 = boundingInfo.boundingBox;
  16177. if (!axisOverlap(box0.directions[0], box0, box1))
  16178. return false;
  16179. if (!axisOverlap(box0.directions[1], box0, box1))
  16180. return false;
  16181. if (!axisOverlap(box0.directions[2], box0, box1))
  16182. return false;
  16183. if (!axisOverlap(box1.directions[0], box0, box1))
  16184. return false;
  16185. if (!axisOverlap(box1.directions[1], box0, box1))
  16186. return false;
  16187. if (!axisOverlap(box1.directions[2], box0, box1))
  16188. return false;
  16189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16190. return false;
  16191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16192. return false;
  16193. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16194. return false;
  16195. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16196. return false;
  16197. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16198. return false;
  16199. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16200. return false;
  16201. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16202. return false;
  16203. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16204. return false;
  16205. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16206. return false;
  16207. return true;
  16208. };
  16209. return BoundingInfo;
  16210. }());
  16211. BABYLON.BoundingInfo = BoundingInfo;
  16212. })(BABYLON || (BABYLON = {}));
  16213. //# sourceMappingURL=babylon.boundingInfo.js.map
  16214. var BABYLON;
  16215. (function (BABYLON) {
  16216. var TransformNode = /** @class */ (function (_super) {
  16217. __extends(TransformNode, _super);
  16218. function TransformNode(name, scene, isPure) {
  16219. if (scene === void 0) { scene = null; }
  16220. if (isPure === void 0) { isPure = true; }
  16221. var _this = _super.call(this, name, scene) || this;
  16222. // Properties
  16223. _this._rotation = BABYLON.Vector3.Zero();
  16224. _this._scaling = BABYLON.Vector3.One();
  16225. _this._isDirty = false;
  16226. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16227. _this.scalingDeterminant = 1;
  16228. _this.infiniteDistance = false;
  16229. _this.position = BABYLON.Vector3.Zero();
  16230. _this._localWorld = BABYLON.Matrix.Zero();
  16231. _this._worldMatrix = BABYLON.Matrix.Zero();
  16232. _this._worldMatrixDeterminant = 0;
  16233. _this._absolutePosition = BABYLON.Vector3.Zero();
  16234. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16235. _this._postMultiplyPivotMatrix = false;
  16236. _this._isWorldMatrixFrozen = false;
  16237. /**
  16238. * An event triggered after the world matrix is updated
  16239. * @type {BABYLON.Observable}
  16240. */
  16241. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16242. _this._nonUniformScaling = false;
  16243. if (isPure) {
  16244. _this.getScene().addTransformNode(_this);
  16245. }
  16246. return _this;
  16247. }
  16248. Object.defineProperty(TransformNode.prototype, "rotation", {
  16249. /**
  16250. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16251. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16252. * Default : (0.0, 0.0, 0.0)
  16253. */
  16254. get: function () {
  16255. return this._rotation;
  16256. },
  16257. set: function (newRotation) {
  16258. this._rotation = newRotation;
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Object.defineProperty(TransformNode.prototype, "scaling", {
  16264. /**
  16265. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16266. * Default : (1.0, 1.0, 1.0)
  16267. */
  16268. get: function () {
  16269. return this._scaling;
  16270. },
  16271. /**
  16272. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16273. * Default : (1.0, 1.0, 1.0)
  16274. */
  16275. set: function (newScaling) {
  16276. this._scaling = newScaling;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16282. /**
  16283. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16284. * It's null by default.
  16285. * 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)
  16286. */
  16287. get: function () {
  16288. return this._rotationQuaternion;
  16289. },
  16290. set: function (quaternion) {
  16291. this._rotationQuaternion = quaternion;
  16292. //reset the rotation vector.
  16293. if (quaternion && this.rotation.length()) {
  16294. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16295. }
  16296. },
  16297. enumerable: true,
  16298. configurable: true
  16299. });
  16300. /**
  16301. * Returns the latest update of the World matrix
  16302. * Returns a Matrix.
  16303. */
  16304. TransformNode.prototype.getWorldMatrix = function () {
  16305. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16306. this.computeWorldMatrix();
  16307. }
  16308. return this._worldMatrix;
  16309. };
  16310. /**
  16311. * Returns the latest update of the World matrix determinant.
  16312. */
  16313. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16314. return this._worldMatrixDeterminant;
  16315. };
  16316. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16317. /**
  16318. * Returns directly the latest state of the mesh World matrix.
  16319. * A Matrix is returned.
  16320. */
  16321. get: function () {
  16322. return this._worldMatrix;
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. /**
  16328. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16329. * Returns the AbstractMesh.
  16330. */
  16331. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16332. this._poseMatrix.copyFrom(matrix);
  16333. return this;
  16334. };
  16335. /**
  16336. * Returns the mesh Pose matrix.
  16337. * Returned object : Matrix
  16338. */
  16339. TransformNode.prototype.getPoseMatrix = function () {
  16340. return this._poseMatrix;
  16341. };
  16342. TransformNode.prototype._isSynchronized = function () {
  16343. if (this._isDirty) {
  16344. return false;
  16345. }
  16346. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16347. return false;
  16348. if (this._cache.pivotMatrixUpdated) {
  16349. return false;
  16350. }
  16351. if (this.infiniteDistance) {
  16352. return false;
  16353. }
  16354. if (!this._cache.position.equals(this.position))
  16355. return false;
  16356. if (this.rotationQuaternion) {
  16357. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16358. return false;
  16359. }
  16360. if (!this._cache.rotation.equals(this.rotation))
  16361. return false;
  16362. if (!this._cache.scaling.equals(this.scaling))
  16363. return false;
  16364. return true;
  16365. };
  16366. TransformNode.prototype._initCache = function () {
  16367. _super.prototype._initCache.call(this);
  16368. this._cache.localMatrixUpdated = false;
  16369. this._cache.position = BABYLON.Vector3.Zero();
  16370. this._cache.scaling = BABYLON.Vector3.Zero();
  16371. this._cache.rotation = BABYLON.Vector3.Zero();
  16372. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16373. this._cache.billboardMode = -1;
  16374. };
  16375. TransformNode.prototype.markAsDirty = function (property) {
  16376. if (property === "rotation") {
  16377. this.rotationQuaternion = null;
  16378. }
  16379. this._currentRenderId = Number.MAX_VALUE;
  16380. this._isDirty = true;
  16381. return this;
  16382. };
  16383. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16384. /**
  16385. * Returns the current mesh absolute position.
  16386. * Retuns a Vector3.
  16387. */
  16388. get: function () {
  16389. return this._absolutePosition;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. /**
  16395. * Sets a new matrix to apply before all other transformation
  16396. * @param matrix defines the transform matrix
  16397. * @returns the current TransformNode
  16398. */
  16399. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16400. return this.setPivotMatrix(matrix, false);
  16401. };
  16402. /**
  16403. * Sets a new pivot matrix to the current node
  16404. * @param matrix defines the new pivot matrix to use
  16405. * @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
  16406. * @returns the current TransformNode
  16407. */
  16408. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16409. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16410. this._pivotMatrix = matrix.clone();
  16411. this._cache.pivotMatrixUpdated = true;
  16412. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16413. if (this._postMultiplyPivotMatrix) {
  16414. if (!this._pivotMatrixInverse) {
  16415. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16416. }
  16417. else {
  16418. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16419. }
  16420. }
  16421. return this;
  16422. };
  16423. /**
  16424. * Returns the mesh pivot matrix.
  16425. * Default : Identity.
  16426. * A Matrix is returned.
  16427. */
  16428. TransformNode.prototype.getPivotMatrix = function () {
  16429. return this._pivotMatrix;
  16430. };
  16431. /**
  16432. * Prevents the World matrix to be computed any longer.
  16433. * Returns the AbstractMesh.
  16434. */
  16435. TransformNode.prototype.freezeWorldMatrix = function () {
  16436. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16437. this.computeWorldMatrix(true);
  16438. this._isWorldMatrixFrozen = true;
  16439. return this;
  16440. };
  16441. /**
  16442. * Allows back the World matrix computation.
  16443. * Returns the AbstractMesh.
  16444. */
  16445. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16446. this._isWorldMatrixFrozen = false;
  16447. this.computeWorldMatrix(true);
  16448. return this;
  16449. };
  16450. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16451. /**
  16452. * True if the World matrix has been frozen.
  16453. * Returns a boolean.
  16454. */
  16455. get: function () {
  16456. return this._isWorldMatrixFrozen;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. /**
  16462. * Retuns the mesh absolute position in the World.
  16463. * Returns a Vector3.
  16464. */
  16465. TransformNode.prototype.getAbsolutePosition = function () {
  16466. this.computeWorldMatrix();
  16467. return this._absolutePosition;
  16468. };
  16469. /**
  16470. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16471. * Returns the AbstractMesh.
  16472. */
  16473. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16474. if (!absolutePosition) {
  16475. return this;
  16476. }
  16477. var absolutePositionX;
  16478. var absolutePositionY;
  16479. var absolutePositionZ;
  16480. if (absolutePosition.x === undefined) {
  16481. if (arguments.length < 3) {
  16482. return this;
  16483. }
  16484. absolutePositionX = arguments[0];
  16485. absolutePositionY = arguments[1];
  16486. absolutePositionZ = arguments[2];
  16487. }
  16488. else {
  16489. absolutePositionX = absolutePosition.x;
  16490. absolutePositionY = absolutePosition.y;
  16491. absolutePositionZ = absolutePosition.z;
  16492. }
  16493. if (this.parent) {
  16494. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16495. invertParentWorldMatrix.invert();
  16496. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16497. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16498. }
  16499. else {
  16500. this.position.x = absolutePositionX;
  16501. this.position.y = absolutePositionY;
  16502. this.position.z = absolutePositionZ;
  16503. }
  16504. return this;
  16505. };
  16506. /**
  16507. * Sets the mesh position in its local space.
  16508. * Returns the AbstractMesh.
  16509. */
  16510. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16511. this.computeWorldMatrix();
  16512. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16513. return this;
  16514. };
  16515. /**
  16516. * Returns the mesh position in the local space from the current World matrix values.
  16517. * Returns a new Vector3.
  16518. */
  16519. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16520. this.computeWorldMatrix();
  16521. var invLocalWorldMatrix = this._localWorld.clone();
  16522. invLocalWorldMatrix.invert();
  16523. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16524. };
  16525. /**
  16526. * Translates the mesh along the passed Vector3 in its local space.
  16527. * Returns the AbstractMesh.
  16528. */
  16529. TransformNode.prototype.locallyTranslate = function (vector3) {
  16530. this.computeWorldMatrix(true);
  16531. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16532. return this;
  16533. };
  16534. /**
  16535. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16536. * @param targetPoint the position (must be in same space as current mesh) to look at
  16537. * @param yawCor optional yaw (y-axis) correction in radians
  16538. * @param pitchCor optional pitch (x-axis) correction in radians
  16539. * @param rollCor optional roll (z-axis) correction in radians
  16540. * @param space the choosen space of the target
  16541. * @returns the TransformNode.
  16542. */
  16543. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16544. if (yawCor === void 0) { yawCor = 0; }
  16545. if (pitchCor === void 0) { pitchCor = 0; }
  16546. if (rollCor === void 0) { rollCor = 0; }
  16547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16548. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16549. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16550. targetPoint.subtractToRef(pos, dv);
  16551. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16552. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16553. var pitch = Math.atan2(dv.y, len);
  16554. if (this.rotationQuaternion) {
  16555. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16556. }
  16557. else {
  16558. this.rotation.x = pitch + pitchCor;
  16559. this.rotation.y = yaw + yawCor;
  16560. this.rotation.z = rollCor;
  16561. }
  16562. return this;
  16563. };
  16564. /**
  16565. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16566. * This Vector3 is expressed in the World space.
  16567. */
  16568. TransformNode.prototype.getDirection = function (localAxis) {
  16569. var result = BABYLON.Vector3.Zero();
  16570. this.getDirectionToRef(localAxis, result);
  16571. return result;
  16572. };
  16573. /**
  16574. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16575. * localAxis is expressed in the mesh local space.
  16576. * result is computed in the Wordl space from the mesh World matrix.
  16577. * Returns the AbstractMesh.
  16578. */
  16579. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16580. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16581. return this;
  16582. };
  16583. /**
  16584. * Sets a new pivot point to the current node
  16585. * @param point defines the new pivot point to use
  16586. * @param space defines if the point is in world or local space (local by default)
  16587. * @returns the current TransformNode
  16588. */
  16589. TransformNode.prototype.setPivotPoint = function (point, space) {
  16590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16591. if (this.getScene().getRenderId() == 0) {
  16592. this.computeWorldMatrix(true);
  16593. }
  16594. var wm = this.getWorldMatrix();
  16595. if (space == BABYLON.Space.WORLD) {
  16596. var tmat = BABYLON.Tmp.Matrix[0];
  16597. wm.invertToRef(tmat);
  16598. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16599. }
  16600. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16601. };
  16602. /**
  16603. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16604. */
  16605. TransformNode.prototype.getPivotPoint = function () {
  16606. var point = BABYLON.Vector3.Zero();
  16607. this.getPivotPointToRef(point);
  16608. return point;
  16609. };
  16610. /**
  16611. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16612. * Returns the AbstractMesh.
  16613. */
  16614. TransformNode.prototype.getPivotPointToRef = function (result) {
  16615. result.x = -this._pivotMatrix.m[12];
  16616. result.y = -this._pivotMatrix.m[13];
  16617. result.z = -this._pivotMatrix.m[14];
  16618. return this;
  16619. };
  16620. /**
  16621. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16622. */
  16623. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16624. var point = BABYLON.Vector3.Zero();
  16625. this.getAbsolutePivotPointToRef(point);
  16626. return point;
  16627. };
  16628. /**
  16629. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16630. * Returns the AbstractMesh.
  16631. */
  16632. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16633. result.x = this._pivotMatrix.m[12];
  16634. result.y = this._pivotMatrix.m[13];
  16635. result.z = this._pivotMatrix.m[14];
  16636. this.getPivotPointToRef(result);
  16637. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16638. return this;
  16639. };
  16640. /**
  16641. * Defines the passed node as the parent of the current node.
  16642. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16643. * Returns the TransformNode.
  16644. */
  16645. TransformNode.prototype.setParent = function (node) {
  16646. if (node === null) {
  16647. var rotation = BABYLON.Tmp.Quaternion[0];
  16648. var position = BABYLON.Tmp.Vector3[0];
  16649. var scale = BABYLON.Tmp.Vector3[1];
  16650. if (this.parent && this.parent.computeWorldMatrix) {
  16651. this.parent.computeWorldMatrix(true);
  16652. }
  16653. this.computeWorldMatrix(true);
  16654. this.getWorldMatrix().decompose(scale, rotation, position);
  16655. if (this.rotationQuaternion) {
  16656. this.rotationQuaternion.copyFrom(rotation);
  16657. }
  16658. else {
  16659. rotation.toEulerAnglesToRef(this.rotation);
  16660. }
  16661. this.scaling.x = scale.x;
  16662. this.scaling.y = scale.y;
  16663. this.scaling.z = scale.z;
  16664. this.position.x = position.x;
  16665. this.position.y = position.y;
  16666. this.position.z = position.z;
  16667. }
  16668. else {
  16669. var rotation = BABYLON.Tmp.Quaternion[0];
  16670. var position = BABYLON.Tmp.Vector3[0];
  16671. var scale = BABYLON.Tmp.Vector3[1];
  16672. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16673. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16674. this.computeWorldMatrix(true);
  16675. node.computeWorldMatrix(true);
  16676. node.getWorldMatrix().invertToRef(invParentMatrix);
  16677. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16678. diffMatrix.decompose(scale, rotation, position);
  16679. if (this.rotationQuaternion) {
  16680. this.rotationQuaternion.copyFrom(rotation);
  16681. }
  16682. else {
  16683. rotation.toEulerAnglesToRef(this.rotation);
  16684. }
  16685. this.position.x = position.x;
  16686. this.position.y = position.y;
  16687. this.position.z = position.z;
  16688. this.scaling.x = scale.x;
  16689. this.scaling.y = scale.y;
  16690. this.scaling.z = scale.z;
  16691. }
  16692. this.parent = node;
  16693. return this;
  16694. };
  16695. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16696. get: function () {
  16697. return this._nonUniformScaling;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16703. if (this._nonUniformScaling === value) {
  16704. return false;
  16705. }
  16706. this._nonUniformScaling = true;
  16707. return true;
  16708. };
  16709. /**
  16710. * Attach the current TransformNode to another TransformNode associated with a bone
  16711. * @param bone Bone affecting the TransformNode
  16712. * @param affectedTransformNode TransformNode associated with the bone
  16713. */
  16714. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16715. this._transformToBoneReferal = affectedTransformNode;
  16716. this.parent = bone;
  16717. if (bone.getWorldMatrix().determinant() < 0) {
  16718. this.scalingDeterminant *= -1;
  16719. }
  16720. return this;
  16721. };
  16722. TransformNode.prototype.detachFromBone = function () {
  16723. if (!this.parent) {
  16724. return this;
  16725. }
  16726. if (this.parent.getWorldMatrix().determinant() < 0) {
  16727. this.scalingDeterminant *= -1;
  16728. }
  16729. this._transformToBoneReferal = null;
  16730. this.parent = null;
  16731. return this;
  16732. };
  16733. /**
  16734. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16735. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16736. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16737. * The passed axis is also normalized.
  16738. * Returns the AbstractMesh.
  16739. */
  16740. TransformNode.prototype.rotate = function (axis, amount, space) {
  16741. axis.normalize();
  16742. if (!this.rotationQuaternion) {
  16743. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16744. this.rotation = BABYLON.Vector3.Zero();
  16745. }
  16746. var rotationQuaternion;
  16747. if (!space || space === BABYLON.Space.LOCAL) {
  16748. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16749. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16750. }
  16751. else {
  16752. if (this.parent) {
  16753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16754. invertParentWorldMatrix.invert();
  16755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16756. }
  16757. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16758. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16764. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16765. * The passed axis is also normalized.
  16766. * Returns the AbstractMesh.
  16767. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16768. */
  16769. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16770. axis.normalize();
  16771. if (!this.rotationQuaternion) {
  16772. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16773. this.rotation.copyFromFloats(0, 0, 0);
  16774. }
  16775. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16776. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16777. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16778. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16779. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16780. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16781. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16782. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16783. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16784. return this;
  16785. };
  16786. /**
  16787. * Translates the mesh along the axis vector for the passed distance in the given space.
  16788. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16789. * Returns the AbstractMesh.
  16790. */
  16791. TransformNode.prototype.translate = function (axis, distance, space) {
  16792. var displacementVector = axis.scale(distance);
  16793. if (!space || space === BABYLON.Space.LOCAL) {
  16794. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16795. this.setPositionWithLocalVector(tempV3);
  16796. }
  16797. else {
  16798. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16799. }
  16800. return this;
  16801. };
  16802. /**
  16803. * Adds a rotation step to the mesh current rotation.
  16804. * x, y, z are Euler angles expressed in radians.
  16805. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16806. * This means this rotation is made in the mesh local space only.
  16807. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16808. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16809. * ```javascript
  16810. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16811. * ```
  16812. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16813. * 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.
  16814. * Returns the AbstractMesh.
  16815. */
  16816. TransformNode.prototype.addRotation = function (x, y, z) {
  16817. var rotationQuaternion;
  16818. if (this.rotationQuaternion) {
  16819. rotationQuaternion = this.rotationQuaternion;
  16820. }
  16821. else {
  16822. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16823. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16824. }
  16825. var accumulation = BABYLON.Tmp.Quaternion[0];
  16826. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16827. rotationQuaternion.multiplyInPlace(accumulation);
  16828. if (!this.rotationQuaternion) {
  16829. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16830. }
  16831. return this;
  16832. };
  16833. /**
  16834. * Computes the mesh World matrix and returns it.
  16835. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16836. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16837. * If the parameter `force`is set to `true`, the actual computation is done.
  16838. * Returns the mesh World Matrix.
  16839. */
  16840. TransformNode.prototype.computeWorldMatrix = function (force) {
  16841. if (this._isWorldMatrixFrozen) {
  16842. return this._worldMatrix;
  16843. }
  16844. if (!force && this.isSynchronized(true)) {
  16845. return this._worldMatrix;
  16846. }
  16847. this._cache.position.copyFrom(this.position);
  16848. this._cache.scaling.copyFrom(this.scaling);
  16849. this._cache.pivotMatrixUpdated = false;
  16850. this._cache.billboardMode = this.billboardMode;
  16851. this._currentRenderId = this.getScene().getRenderId();
  16852. this._isDirty = false;
  16853. // Scaling
  16854. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16855. // Rotation
  16856. //rotate, if quaternion is set and rotation was used
  16857. if (this.rotationQuaternion) {
  16858. var len = this.rotation.length();
  16859. if (len) {
  16860. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16861. this.rotation.copyFromFloats(0, 0, 0);
  16862. }
  16863. }
  16864. if (this.rotationQuaternion) {
  16865. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16866. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16867. }
  16868. else {
  16869. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16870. this._cache.rotation.copyFrom(this.rotation);
  16871. }
  16872. // Translation
  16873. var camera = this.getScene().activeCamera;
  16874. if (this.infiniteDistance && !this.parent && camera) {
  16875. var cameraWorldMatrix = camera.getWorldMatrix();
  16876. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16877. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16878. }
  16879. else {
  16880. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16881. }
  16882. // Composing transformations
  16883. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16884. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16885. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16886. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16887. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16888. // Need to decompose each rotation here
  16889. var currentPosition = BABYLON.Tmp.Vector3[3];
  16890. if (this.parent && this.parent.getWorldMatrix) {
  16891. if (this._transformToBoneReferal) {
  16892. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16893. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16894. }
  16895. else {
  16896. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16897. }
  16898. }
  16899. else {
  16900. currentPosition.copyFrom(this.position);
  16901. }
  16902. currentPosition.subtractInPlace(camera.globalPosition);
  16903. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16904. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16905. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16906. }
  16907. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16908. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16909. }
  16910. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16911. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16912. }
  16913. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16914. }
  16915. else {
  16916. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16917. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16918. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16919. }
  16920. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16921. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16922. }
  16923. // Local world
  16924. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16925. // Parent
  16926. if (this.parent && this.parent.getWorldMatrix) {
  16927. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16928. if (this._transformToBoneReferal) {
  16929. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16930. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16931. }
  16932. else {
  16933. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16934. }
  16935. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16936. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16937. this._worldMatrix.copyFrom(this._localWorld);
  16938. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16939. }
  16940. else {
  16941. if (this._transformToBoneReferal) {
  16942. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16943. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16944. }
  16945. else {
  16946. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16947. }
  16948. }
  16949. this._markSyncedWithParent();
  16950. }
  16951. else {
  16952. this._worldMatrix.copyFrom(this._localWorld);
  16953. }
  16954. // Post multiply inverse of pivotMatrix
  16955. if (this._postMultiplyPivotMatrix) {
  16956. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16957. }
  16958. // Normal matrix
  16959. if (this.scaling.isNonUniform) {
  16960. this._updateNonUniformScalingState(true);
  16961. }
  16962. else if (this.parent && this.parent._nonUniformScaling) {
  16963. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16964. }
  16965. else {
  16966. this._updateNonUniformScalingState(false);
  16967. }
  16968. this._afterComputeWorldMatrix();
  16969. // Absolute position
  16970. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16971. // Callbacks
  16972. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16973. if (!this._poseMatrix) {
  16974. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16975. }
  16976. // Cache the determinant
  16977. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16978. return this._worldMatrix;
  16979. };
  16980. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16981. };
  16982. /**
  16983. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16984. * @param func: callback function to add
  16985. *
  16986. * Returns the TransformNode.
  16987. */
  16988. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16989. this.onAfterWorldMatrixUpdateObservable.add(func);
  16990. return this;
  16991. };
  16992. /**
  16993. * Removes a registered callback function.
  16994. * Returns the TransformNode.
  16995. */
  16996. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16997. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16998. return this;
  16999. };
  17000. /**
  17001. * Clone the current transform node
  17002. * Returns the new transform node
  17003. * @param name Name of the new clone
  17004. * @param newParent New parent for the clone
  17005. * @param doNotCloneChildren Do not clone children hierarchy
  17006. */
  17007. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17008. var _this = this;
  17009. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17010. result.name = name;
  17011. result.id = name;
  17012. if (newParent) {
  17013. result.parent = newParent;
  17014. }
  17015. if (!doNotCloneChildren) {
  17016. // Children
  17017. var directDescendants = this.getDescendants(true);
  17018. for (var index = 0; index < directDescendants.length; index++) {
  17019. var child = directDescendants[index];
  17020. if (child.clone) {
  17021. child.clone(name + "." + child.name, result);
  17022. }
  17023. }
  17024. }
  17025. return result;
  17026. };
  17027. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17028. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17029. serializationObject.type = this.getClassName();
  17030. // Parent
  17031. if (this.parent) {
  17032. serializationObject.parentId = this.parent.id;
  17033. }
  17034. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17035. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17036. }
  17037. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17038. serializationObject.isEnabled = this.isEnabled();
  17039. // Parent
  17040. if (this.parent) {
  17041. serializationObject.parentId = this.parent.id;
  17042. }
  17043. return serializationObject;
  17044. };
  17045. // Statics
  17046. /**
  17047. * Returns a new TransformNode object parsed from the source provided.
  17048. * The parameter `parsedMesh` is the source.
  17049. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17050. */
  17051. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17052. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17053. if (BABYLON.Tags) {
  17054. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17055. }
  17056. if (parsedTransformNode.localMatrix) {
  17057. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17058. }
  17059. else if (parsedTransformNode.pivotMatrix) {
  17060. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17061. }
  17062. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17063. // Parent
  17064. if (parsedTransformNode.parentId) {
  17065. transformNode._waitingParentId = parsedTransformNode.parentId;
  17066. }
  17067. return transformNode;
  17068. };
  17069. /**
  17070. * Disposes the TransformNode.
  17071. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17072. * Returns nothing.
  17073. */
  17074. TransformNode.prototype.dispose = function (doNotRecurse) {
  17075. // Animations
  17076. this.getScene().stopAnimation(this);
  17077. // Remove from scene
  17078. this.getScene().removeTransformNode(this);
  17079. if (!doNotRecurse) {
  17080. // Children
  17081. var objects = this.getDescendants(true);
  17082. for (var index = 0; index < objects.length; index++) {
  17083. objects[index].dispose();
  17084. }
  17085. }
  17086. else {
  17087. var childMeshes = this.getChildMeshes(true);
  17088. for (index = 0; index < childMeshes.length; index++) {
  17089. var child = childMeshes[index];
  17090. child.parent = null;
  17091. child.computeWorldMatrix(true);
  17092. }
  17093. }
  17094. this.onAfterWorldMatrixUpdateObservable.clear();
  17095. _super.prototype.dispose.call(this);
  17096. };
  17097. // Statics
  17098. TransformNode.BILLBOARDMODE_NONE = 0;
  17099. TransformNode.BILLBOARDMODE_X = 1;
  17100. TransformNode.BILLBOARDMODE_Y = 2;
  17101. TransformNode.BILLBOARDMODE_Z = 4;
  17102. TransformNode.BILLBOARDMODE_ALL = 7;
  17103. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17104. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17105. __decorate([
  17106. BABYLON.serializeAsVector3()
  17107. ], TransformNode.prototype, "_rotation", void 0);
  17108. __decorate([
  17109. BABYLON.serializeAsQuaternion()
  17110. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17111. __decorate([
  17112. BABYLON.serializeAsVector3()
  17113. ], TransformNode.prototype, "_scaling", void 0);
  17114. __decorate([
  17115. BABYLON.serialize()
  17116. ], TransformNode.prototype, "billboardMode", void 0);
  17117. __decorate([
  17118. BABYLON.serialize()
  17119. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17120. __decorate([
  17121. BABYLON.serialize()
  17122. ], TransformNode.prototype, "infiniteDistance", void 0);
  17123. __decorate([
  17124. BABYLON.serializeAsVector3()
  17125. ], TransformNode.prototype, "position", void 0);
  17126. return TransformNode;
  17127. }(BABYLON.Node));
  17128. BABYLON.TransformNode = TransformNode;
  17129. })(BABYLON || (BABYLON = {}));
  17130. //# sourceMappingURL=babylon.transformNode.js.map
  17131. var BABYLON;
  17132. (function (BABYLON) {
  17133. var AbstractMesh = /** @class */ (function (_super) {
  17134. __extends(AbstractMesh, _super);
  17135. // Constructor
  17136. function AbstractMesh(name, scene) {
  17137. if (scene === void 0) { scene = null; }
  17138. var _this = _super.call(this, name, scene, false) || this;
  17139. _this._facetNb = 0; // facet number
  17140. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17141. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17142. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17143. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17144. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17145. _this._subDiv = {
  17146. max: 1,
  17147. X: 1,
  17148. Y: 1,
  17149. Z: 1
  17150. };
  17151. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17152. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17153. // Events
  17154. /**
  17155. * An event triggered when this mesh collides with another one
  17156. * @type {BABYLON.Observable}
  17157. */
  17158. _this.onCollideObservable = new BABYLON.Observable();
  17159. /**
  17160. * An event triggered when the collision's position changes
  17161. * @type {BABYLON.Observable}
  17162. */
  17163. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17164. /**
  17165. * An event triggered when material is changed
  17166. * @type {BABYLON.Observable}
  17167. */
  17168. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17169. // Properties
  17170. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17171. /**
  17172. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17173. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17174. * or
  17175. * 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.
  17176. * for more info check WebGl documentations
  17177. */
  17178. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17179. /**
  17180. * 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:
  17181. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17182. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17183. * 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.
  17184. */
  17185. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17186. /**
  17187. * 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.
  17188. * The default value is -1 which means don't break the query and wait till the result.
  17189. */
  17190. _this.occlusionRetryCount = -1;
  17191. _this._occlusionInternalRetryCounter = 0;
  17192. _this._isOccluded = false;
  17193. _this._isOcclusionQueryInProgress = false;
  17194. _this._visibility = 1.0;
  17195. _this.alphaIndex = Number.MAX_VALUE;
  17196. _this.isVisible = true;
  17197. _this.isPickable = true;
  17198. _this.showBoundingBox = false;
  17199. _this.showSubMeshesBoundingBox = false;
  17200. _this.isBlocker = false;
  17201. _this.enablePointerMoveEvents = false;
  17202. _this.renderingGroupId = 0;
  17203. _this._receiveShadows = false;
  17204. _this.renderOutline = false;
  17205. _this.outlineColor = BABYLON.Color3.Red();
  17206. _this.outlineWidth = 0.02;
  17207. _this.renderOverlay = false;
  17208. _this.overlayColor = BABYLON.Color3.Red();
  17209. _this.overlayAlpha = 0.5;
  17210. _this._hasVertexAlpha = false;
  17211. _this._useVertexColors = true;
  17212. _this._computeBonesUsingShaders = true;
  17213. _this._numBoneInfluencers = 4;
  17214. _this._applyFog = true;
  17215. _this.useOctreeForRenderingSelection = true;
  17216. _this.useOctreeForPicking = true;
  17217. _this.useOctreeForCollisions = true;
  17218. _this._layerMask = 0x0FFFFFFF;
  17219. /**
  17220. * True if the mesh must be rendered in any case.
  17221. */
  17222. _this.alwaysSelectAsActiveMesh = false;
  17223. /**
  17224. * This scene's action manager
  17225. * @type {BABYLON.ActionManager}
  17226. */
  17227. _this.actionManager = null;
  17228. // Physics
  17229. _this.physicsImpostor = null;
  17230. // Collisions
  17231. _this._checkCollisions = false;
  17232. _this._collisionMask = -1;
  17233. _this._collisionGroup = -1;
  17234. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17235. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17236. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17237. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17238. // Edges
  17239. _this.edgesWidth = 1;
  17240. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17241. // Cache
  17242. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17243. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17244. _this._renderId = 0;
  17245. _this._intersectionsInProgress = new Array();
  17246. _this._unIndexed = false;
  17247. _this._lightSources = new Array();
  17248. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17249. if (collidedMesh === void 0) { collidedMesh = null; }
  17250. //TODO move this to the collision coordinator!
  17251. if (_this.getScene().workerCollisions)
  17252. newPosition.multiplyInPlace(_this._collider._radius);
  17253. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17254. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17255. _this.position.addInPlace(_this._diffPositionForCollisions);
  17256. }
  17257. if (collidedMesh) {
  17258. _this.onCollideObservable.notifyObservers(collidedMesh);
  17259. }
  17260. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17261. };
  17262. _this.getScene().addMesh(_this);
  17263. _this._resyncLightSources();
  17264. return _this;
  17265. }
  17266. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17267. get: function () {
  17268. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17269. },
  17270. enumerable: true,
  17271. configurable: true
  17272. });
  17273. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17274. get: function () {
  17275. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17281. get: function () {
  17282. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17283. },
  17284. enumerable: true,
  17285. configurable: true
  17286. });
  17287. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17288. get: function () {
  17289. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17290. },
  17291. enumerable: true,
  17292. configurable: true
  17293. });
  17294. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17295. get: function () {
  17296. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17297. },
  17298. enumerable: true,
  17299. configurable: true
  17300. });
  17301. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17302. /**
  17303. * Read-only : the number of facets in the mesh
  17304. */
  17305. get: function () {
  17306. return this._facetNb;
  17307. },
  17308. enumerable: true,
  17309. configurable: true
  17310. });
  17311. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17312. /**
  17313. * The number (integer) of subdivisions per axis in the partioning space
  17314. */
  17315. get: function () {
  17316. return this._partitioningSubdivisions;
  17317. },
  17318. set: function (nb) {
  17319. this._partitioningSubdivisions = nb;
  17320. },
  17321. enumerable: true,
  17322. configurable: true
  17323. });
  17324. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17325. /**
  17326. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17327. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17328. */
  17329. get: function () {
  17330. return this._partitioningBBoxRatio;
  17331. },
  17332. set: function (ratio) {
  17333. this._partitioningBBoxRatio = ratio;
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17339. /**
  17340. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17341. * Works only for updatable meshes.
  17342. * Doesn't work with multi-materials.
  17343. */
  17344. get: function () {
  17345. return this._facetDepthSort;
  17346. },
  17347. set: function (sort) {
  17348. this._facetDepthSort = sort;
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17354. /**
  17355. * The location (Vector3) where the facet depth sort must be computed from.
  17356. * By default, the active camera position.
  17357. * Used only when facet depth sort is enabled.
  17358. */
  17359. get: function () {
  17360. return this._facetDepthSortFrom;
  17361. },
  17362. set: function (location) {
  17363. this._facetDepthSortFrom = location;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17369. /**
  17370. * Read-only boolean : is the feature facetData enabled ?
  17371. */
  17372. get: function () {
  17373. return this._facetDataEnabled;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17379. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17380. return false;
  17381. }
  17382. this._markSubMeshesAsMiscDirty();
  17383. return true;
  17384. };
  17385. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17386. set: function (callback) {
  17387. if (this._onCollideObserver) {
  17388. this.onCollideObservable.remove(this._onCollideObserver);
  17389. }
  17390. this._onCollideObserver = this.onCollideObservable.add(callback);
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17396. set: function (callback) {
  17397. if (this._onCollisionPositionChangeObserver) {
  17398. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17399. }
  17400. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17401. },
  17402. enumerable: true,
  17403. configurable: true
  17404. });
  17405. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17406. /**
  17407. * Property isOccluded : 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.
  17408. */
  17409. get: function () {
  17410. return this._isOccluded;
  17411. },
  17412. set: function (value) {
  17413. this._isOccluded = value;
  17414. },
  17415. enumerable: true,
  17416. configurable: true
  17417. });
  17418. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17419. /**
  17420. * Flag to check the progress status of the query
  17421. */
  17422. get: function () {
  17423. return this._isOcclusionQueryInProgress;
  17424. },
  17425. enumerable: true,
  17426. configurable: true
  17427. });
  17428. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17429. /**
  17430. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17431. */
  17432. get: function () {
  17433. return this._visibility;
  17434. },
  17435. /**
  17436. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17437. */
  17438. set: function (value) {
  17439. if (this._visibility === value) {
  17440. return;
  17441. }
  17442. this._visibility = value;
  17443. this._markSubMeshesAsMiscDirty();
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. Object.defineProperty(AbstractMesh.prototype, "material", {
  17449. get: function () {
  17450. return this._material;
  17451. },
  17452. set: function (value) {
  17453. if (this._material === value) {
  17454. return;
  17455. }
  17456. this._material = value;
  17457. if (this.onMaterialChangedObservable.hasObservers) {
  17458. this.onMaterialChangedObservable.notifyObservers(this);
  17459. }
  17460. if (!this.subMeshes) {
  17461. return;
  17462. }
  17463. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17464. var subMesh = _a[_i];
  17465. subMesh.setEffect(null);
  17466. }
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17472. get: function () {
  17473. return this._receiveShadows;
  17474. },
  17475. set: function (value) {
  17476. if (this._receiveShadows === value) {
  17477. return;
  17478. }
  17479. this._receiveShadows = value;
  17480. this._markSubMeshesAsLightDirty();
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17486. get: function () {
  17487. return this._hasVertexAlpha;
  17488. },
  17489. set: function (value) {
  17490. if (this._hasVertexAlpha === value) {
  17491. return;
  17492. }
  17493. this._hasVertexAlpha = value;
  17494. this._markSubMeshesAsAttributesDirty();
  17495. this._markSubMeshesAsMiscDirty();
  17496. },
  17497. enumerable: true,
  17498. configurable: true
  17499. });
  17500. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17501. get: function () {
  17502. return this._useVertexColors;
  17503. },
  17504. set: function (value) {
  17505. if (this._useVertexColors === value) {
  17506. return;
  17507. }
  17508. this._useVertexColors = value;
  17509. this._markSubMeshesAsAttributesDirty();
  17510. },
  17511. enumerable: true,
  17512. configurable: true
  17513. });
  17514. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17515. get: function () {
  17516. return this._computeBonesUsingShaders;
  17517. },
  17518. set: function (value) {
  17519. if (this._computeBonesUsingShaders === value) {
  17520. return;
  17521. }
  17522. this._computeBonesUsingShaders = value;
  17523. this._markSubMeshesAsAttributesDirty();
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17529. get: function () {
  17530. return this._numBoneInfluencers;
  17531. },
  17532. set: function (value) {
  17533. if (this._numBoneInfluencers === value) {
  17534. return;
  17535. }
  17536. this._numBoneInfluencers = value;
  17537. this._markSubMeshesAsAttributesDirty();
  17538. },
  17539. enumerable: true,
  17540. configurable: true
  17541. });
  17542. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17543. get: function () {
  17544. return this._applyFog;
  17545. },
  17546. set: function (value) {
  17547. if (this._applyFog === value) {
  17548. return;
  17549. }
  17550. this._applyFog = value;
  17551. this._markSubMeshesAsMiscDirty();
  17552. },
  17553. enumerable: true,
  17554. configurable: true
  17555. });
  17556. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17557. get: function () {
  17558. return this._layerMask;
  17559. },
  17560. set: function (value) {
  17561. if (value === this._layerMask) {
  17562. return;
  17563. }
  17564. this._layerMask = value;
  17565. this._resyncLightSources();
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17571. get: function () {
  17572. return this._collisionMask;
  17573. },
  17574. set: function (mask) {
  17575. this._collisionMask = !isNaN(mask) ? mask : -1;
  17576. },
  17577. enumerable: true,
  17578. configurable: true
  17579. });
  17580. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17581. get: function () {
  17582. return this._collisionGroup;
  17583. },
  17584. set: function (mask) {
  17585. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17591. get: function () {
  17592. return null;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17598. get: function () {
  17599. return this._skeleton;
  17600. },
  17601. set: function (value) {
  17602. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17603. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17604. }
  17605. if (value && value.needInitialSkinMatrix) {
  17606. value._registerMeshWithPoseMatrix(this);
  17607. }
  17608. this._skeleton = value;
  17609. if (!this._skeleton) {
  17610. this._bonesTransformMatrices = null;
  17611. }
  17612. this._markSubMeshesAsAttributesDirty();
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. /**
  17618. * Returns the string "AbstractMesh"
  17619. */
  17620. AbstractMesh.prototype.getClassName = function () {
  17621. return "AbstractMesh";
  17622. };
  17623. /**
  17624. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17625. */
  17626. AbstractMesh.prototype.toString = function (fullDetails) {
  17627. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17628. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17629. if (this._skeleton) {
  17630. ret += ", skeleton: " + this._skeleton.name;
  17631. }
  17632. if (fullDetails) {
  17633. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17634. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17635. }
  17636. return ret;
  17637. };
  17638. AbstractMesh.prototype._rebuild = function () {
  17639. if (this._occlusionQuery) {
  17640. this._occlusionQuery = null;
  17641. }
  17642. if (this._edgesRenderer) {
  17643. this._edgesRenderer._rebuild();
  17644. }
  17645. if (!this.subMeshes) {
  17646. return;
  17647. }
  17648. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17649. var subMesh = _a[_i];
  17650. subMesh._rebuild();
  17651. }
  17652. };
  17653. AbstractMesh.prototype._resyncLightSources = function () {
  17654. this._lightSources.length = 0;
  17655. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17656. var light = _a[_i];
  17657. if (!light.isEnabled()) {
  17658. continue;
  17659. }
  17660. if (light.canAffectMesh(this)) {
  17661. this._lightSources.push(light);
  17662. }
  17663. }
  17664. this._markSubMeshesAsLightDirty();
  17665. };
  17666. AbstractMesh.prototype._resyncLighSource = function (light) {
  17667. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17668. var index = this._lightSources.indexOf(light);
  17669. if (index === -1) {
  17670. if (!isIn) {
  17671. return;
  17672. }
  17673. this._lightSources.push(light);
  17674. }
  17675. else {
  17676. if (isIn) {
  17677. return;
  17678. }
  17679. this._lightSources.splice(index, 1);
  17680. }
  17681. this._markSubMeshesAsLightDirty();
  17682. };
  17683. AbstractMesh.prototype._removeLightSource = function (light) {
  17684. var index = this._lightSources.indexOf(light);
  17685. if (index === -1) {
  17686. return;
  17687. }
  17688. this._lightSources.splice(index, 1);
  17689. this._markSubMeshesAsLightDirty();
  17690. };
  17691. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17692. if (!this.subMeshes) {
  17693. return;
  17694. }
  17695. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17696. var subMesh = _a[_i];
  17697. if (subMesh._materialDefines) {
  17698. func(subMesh._materialDefines);
  17699. }
  17700. }
  17701. };
  17702. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17703. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17704. };
  17705. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17706. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17707. };
  17708. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17709. if (!this.subMeshes) {
  17710. return;
  17711. }
  17712. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17713. var subMesh = _a[_i];
  17714. var material = subMesh.getMaterial();
  17715. if (material) {
  17716. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17717. }
  17718. }
  17719. };
  17720. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17721. /**
  17722. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17723. * Default : (1.0, 1.0, 1.0)
  17724. */
  17725. get: function () {
  17726. return this._scaling;
  17727. },
  17728. /**
  17729. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17730. * Default : (1.0, 1.0, 1.0)
  17731. */
  17732. set: function (newScaling) {
  17733. this._scaling = newScaling;
  17734. if (this.physicsImpostor) {
  17735. this.physicsImpostor.forceUpdate();
  17736. }
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. // Methods
  17742. /**
  17743. * Disables the mesh edger rendering mode.
  17744. * Returns the AbstractMesh.
  17745. */
  17746. AbstractMesh.prototype.disableEdgesRendering = function () {
  17747. if (this._edgesRenderer) {
  17748. this._edgesRenderer.dispose();
  17749. this._edgesRenderer = null;
  17750. }
  17751. return this;
  17752. };
  17753. /**
  17754. * Enables the edge rendering mode on the mesh.
  17755. * This mode makes the mesh edges visible.
  17756. * Returns the AbstractMesh.
  17757. */
  17758. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17759. if (epsilon === void 0) { epsilon = 0.95; }
  17760. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17761. this.disableEdgesRendering();
  17762. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17763. return this;
  17764. };
  17765. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17766. /**
  17767. * Returns true if the mesh is blocked. Used by the class Mesh.
  17768. * Returns the boolean `false` by default.
  17769. */
  17770. get: function () {
  17771. return false;
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. /**
  17777. * Returns the mesh itself by default, used by the class Mesh.
  17778. * Returned type : AbstractMesh
  17779. */
  17780. AbstractMesh.prototype.getLOD = function (camera) {
  17781. return this;
  17782. };
  17783. /**
  17784. * Returns 0 by default, used by the class Mesh.
  17785. * Returns an integer.
  17786. */
  17787. AbstractMesh.prototype.getTotalVertices = function () {
  17788. return 0;
  17789. };
  17790. /**
  17791. * Returns null by default, used by the class Mesh.
  17792. * Returned type : integer array
  17793. */
  17794. AbstractMesh.prototype.getIndices = function () {
  17795. return null;
  17796. };
  17797. /**
  17798. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17799. * Returned type : float array or Float32Array
  17800. */
  17801. AbstractMesh.prototype.getVerticesData = function (kind) {
  17802. return null;
  17803. };
  17804. /**
  17805. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17806. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17807. * The `data` are either a numeric array either a Float32Array.
  17808. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17809. * 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).
  17810. * Note that a new underlying VertexBuffer object is created each call.
  17811. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17812. *
  17813. * Possible `kind` values :
  17814. * - BABYLON.VertexBuffer.PositionKind
  17815. * - BABYLON.VertexBuffer.UVKind
  17816. * - BABYLON.VertexBuffer.UV2Kind
  17817. * - BABYLON.VertexBuffer.UV3Kind
  17818. * - BABYLON.VertexBuffer.UV4Kind
  17819. * - BABYLON.VertexBuffer.UV5Kind
  17820. * - BABYLON.VertexBuffer.UV6Kind
  17821. * - BABYLON.VertexBuffer.ColorKind
  17822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17826. *
  17827. * Returns the Mesh.
  17828. */
  17829. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17830. return this;
  17831. };
  17832. /**
  17833. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17834. * If the mesh has no geometry, it is simply returned as it is.
  17835. * The `data` are either a numeric array either a Float32Array.
  17836. * No new underlying VertexBuffer object is created.
  17837. * 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.
  17838. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17839. *
  17840. * Possible `kind` values :
  17841. * - BABYLON.VertexBuffer.PositionKind
  17842. * - BABYLON.VertexBuffer.UVKind
  17843. * - BABYLON.VertexBuffer.UV2Kind
  17844. * - BABYLON.VertexBuffer.UV3Kind
  17845. * - BABYLON.VertexBuffer.UV4Kind
  17846. * - BABYLON.VertexBuffer.UV5Kind
  17847. * - BABYLON.VertexBuffer.UV6Kind
  17848. * - BABYLON.VertexBuffer.ColorKind
  17849. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17850. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17851. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17852. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17853. *
  17854. * Returns the Mesh.
  17855. */
  17856. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17857. return this;
  17858. };
  17859. /**
  17860. * Sets the mesh indices.
  17861. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17862. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17863. * This method creates a new index buffer each call.
  17864. * Returns the Mesh.
  17865. */
  17866. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17867. return this;
  17868. };
  17869. /** Returns false by default, used by the class Mesh.
  17870. * Returns a boolean
  17871. */
  17872. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17873. return false;
  17874. };
  17875. /**
  17876. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17877. * Returns a BoundingInfo
  17878. */
  17879. AbstractMesh.prototype.getBoundingInfo = function () {
  17880. if (this._masterMesh) {
  17881. return this._masterMesh.getBoundingInfo();
  17882. }
  17883. if (!this._boundingInfo) {
  17884. // this._boundingInfo is being created here
  17885. this._updateBoundingInfo();
  17886. }
  17887. // cannot be null.
  17888. return this._boundingInfo;
  17889. };
  17890. /**
  17891. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17892. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17893. */
  17894. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17895. if (includeDescendants === void 0) { includeDescendants = true; }
  17896. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17897. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17898. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17899. if (maxDimension === 0) {
  17900. return this;
  17901. }
  17902. var scale = 1 / maxDimension;
  17903. this.scaling.scaleInPlace(scale);
  17904. return this;
  17905. };
  17906. /**
  17907. * Sets a mesh new object BoundingInfo.
  17908. * Returns the AbstractMesh.
  17909. */
  17910. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17911. this._boundingInfo = boundingInfo;
  17912. return this;
  17913. };
  17914. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17915. get: function () {
  17916. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. AbstractMesh.prototype._preActivate = function () {
  17922. };
  17923. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17924. };
  17925. AbstractMesh.prototype._activate = function (renderId) {
  17926. this._renderId = renderId;
  17927. };
  17928. /**
  17929. * Returns the latest update of the World matrix
  17930. * Returns a Matrix.
  17931. */
  17932. AbstractMesh.prototype.getWorldMatrix = function () {
  17933. if (this._masterMesh) {
  17934. return this._masterMesh.getWorldMatrix();
  17935. }
  17936. return _super.prototype.getWorldMatrix.call(this);
  17937. };
  17938. /**
  17939. * Returns the latest update of the World matrix determinant.
  17940. */
  17941. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17942. if (this._masterMesh) {
  17943. return this._masterMesh._getWorldMatrixDeterminant();
  17944. }
  17945. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17946. };
  17947. // ================================== Point of View Movement =================================
  17948. /**
  17949. * Perform relative position change from the point of view of behind the front of the mesh.
  17950. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17951. * Supports definition of mesh facing forward or backward.
  17952. * @param {number} amountRight
  17953. * @param {number} amountUp
  17954. * @param {number} amountForward
  17955. *
  17956. * Returns the AbstractMesh.
  17957. */
  17958. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17959. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17960. return this;
  17961. };
  17962. /**
  17963. * Calculate relative position change from the point of view of behind the front of the mesh.
  17964. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17965. * Supports definition of mesh facing forward or backward.
  17966. * @param {number} amountRight
  17967. * @param {number} amountUp
  17968. * @param {number} amountForward
  17969. *
  17970. * Returns a new Vector3.
  17971. */
  17972. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17973. var rotMatrix = new BABYLON.Matrix();
  17974. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17975. rotQuaternion.toRotationMatrix(rotMatrix);
  17976. var translationDelta = BABYLON.Vector3.Zero();
  17977. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17978. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17979. return translationDelta;
  17980. };
  17981. // ================================== Point of View Rotation =================================
  17982. /**
  17983. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17984. * Supports definition of mesh facing forward or backward.
  17985. * @param {number} flipBack
  17986. * @param {number} twirlClockwise
  17987. * @param {number} tiltRight
  17988. *
  17989. * Returns the AbstractMesh.
  17990. */
  17991. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17992. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17993. return this;
  17994. };
  17995. /**
  17996. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17997. * Supports definition of mesh facing forward or backward.
  17998. * @param {number} flipBack
  17999. * @param {number} twirlClockwise
  18000. * @param {number} tiltRight
  18001. *
  18002. * Returns a new Vector3.
  18003. */
  18004. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18005. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18006. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18007. };
  18008. /**
  18009. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18010. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18011. */
  18012. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18013. if (includeDescendants === void 0) { includeDescendants = true; }
  18014. this.computeWorldMatrix(true);
  18015. var min;
  18016. var max;
  18017. var boundingInfo = this.getBoundingInfo();
  18018. if (!this.subMeshes) {
  18019. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18020. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18021. }
  18022. else {
  18023. min = boundingInfo.boundingBox.minimumWorld;
  18024. max = boundingInfo.boundingBox.maximumWorld;
  18025. }
  18026. if (includeDescendants) {
  18027. var descendants = this.getDescendants(false);
  18028. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18029. var descendant = descendants_1[_i];
  18030. var childMesh = descendant;
  18031. childMesh.computeWorldMatrix(true);
  18032. //make sure we have the needed params to get mix and max
  18033. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18034. continue;
  18035. }
  18036. var childBoundingInfo = childMesh.getBoundingInfo();
  18037. var boundingBox = childBoundingInfo.boundingBox;
  18038. var minBox = boundingBox.minimumWorld;
  18039. var maxBox = boundingBox.maximumWorld;
  18040. BABYLON.Tools.CheckExtends(minBox, min, max);
  18041. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18042. }
  18043. }
  18044. return {
  18045. min: min,
  18046. max: max
  18047. };
  18048. };
  18049. /**
  18050. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18051. * Returns the AbstractMesh.
  18052. */
  18053. AbstractMesh.prototype._updateBoundingInfo = function () {
  18054. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18055. this._boundingInfo.update(this.worldMatrixFromCache);
  18056. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18057. return this;
  18058. };
  18059. /**
  18060. * Update a mesh's children BoundingInfo objects only.
  18061. * Returns the AbstractMesh.
  18062. */
  18063. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18064. if (!this.subMeshes) {
  18065. return this;
  18066. }
  18067. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18068. var subMesh = this.subMeshes[subIndex];
  18069. if (!subMesh.IsGlobal) {
  18070. subMesh.updateBoundingInfo(matrix);
  18071. }
  18072. }
  18073. return this;
  18074. };
  18075. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18076. // Bounding info
  18077. this._updateBoundingInfo();
  18078. };
  18079. /**
  18080. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18081. * A mesh is in the frustum if its bounding box intersects the frustum.
  18082. * Boolean returned.
  18083. */
  18084. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18085. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18086. };
  18087. /**
  18088. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18089. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18090. * Boolean returned.
  18091. */
  18092. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18093. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18094. ;
  18095. };
  18096. /**
  18097. * True if the mesh intersects another mesh or a SolidParticle object.
  18098. * 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)
  18099. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18100. * Returns a boolean.
  18101. */
  18102. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18103. if (precise === void 0) { precise = false; }
  18104. if (!this._boundingInfo || !mesh._boundingInfo) {
  18105. return false;
  18106. }
  18107. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18108. return true;
  18109. }
  18110. if (includeDescendants) {
  18111. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18112. var child = _a[_i];
  18113. if (child.intersectsMesh(mesh, precise, true)) {
  18114. return true;
  18115. }
  18116. }
  18117. }
  18118. return false;
  18119. };
  18120. /**
  18121. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18122. * Returns a boolean.
  18123. */
  18124. AbstractMesh.prototype.intersectsPoint = function (point) {
  18125. if (!this._boundingInfo) {
  18126. return false;
  18127. }
  18128. return this._boundingInfo.intersectsPoint(point);
  18129. };
  18130. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18131. return this.physicsImpostor;
  18132. };
  18133. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18134. if (camera === void 0) { camera = null; }
  18135. if (!camera) {
  18136. camera = this.getScene().activeCamera;
  18137. }
  18138. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18139. };
  18140. /**
  18141. * Returns the distance from the mesh to the active camera.
  18142. * Returns a float.
  18143. */
  18144. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18145. if (camera === void 0) { camera = null; }
  18146. if (!camera) {
  18147. camera = this.getScene().activeCamera;
  18148. }
  18149. return this.absolutePosition.subtract(camera.position).length();
  18150. };
  18151. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18152. if (!this.physicsImpostor) {
  18153. return this;
  18154. }
  18155. this.physicsImpostor.applyImpulse(force, contactPoint);
  18156. return this;
  18157. };
  18158. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18159. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18160. return this;
  18161. }
  18162. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18163. mainPivot: pivot1,
  18164. connectedPivot: pivot2,
  18165. nativeParams: options
  18166. });
  18167. return this;
  18168. };
  18169. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18170. // Collisions
  18171. /**
  18172. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18173. * Default `false`.
  18174. */
  18175. get: function () {
  18176. return this._checkCollisions;
  18177. },
  18178. set: function (collisionEnabled) {
  18179. this._checkCollisions = collisionEnabled;
  18180. if (this.getScene().workerCollisions) {
  18181. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18182. }
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18188. /**
  18189. * Gets Collider object used to compute collisions (not physics)
  18190. */
  18191. get: function () {
  18192. return this._collider;
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18198. var globalPosition = this.getAbsolutePosition();
  18199. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18200. if (!this._collider) {
  18201. this._collider = new BABYLON.Collider();
  18202. }
  18203. this._collider._radius = this.ellipsoid;
  18204. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18205. return this;
  18206. };
  18207. // Submeshes octree
  18208. /**
  18209. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18210. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18211. * Returns an Octree of submeshes.
  18212. */
  18213. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18214. if (maxCapacity === void 0) { maxCapacity = 64; }
  18215. if (maxDepth === void 0) { maxDepth = 2; }
  18216. if (!this._submeshesOctree) {
  18217. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18218. }
  18219. this.computeWorldMatrix(true);
  18220. var boundingInfo = this.getBoundingInfo();
  18221. // Update octree
  18222. var bbox = boundingInfo.boundingBox;
  18223. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18224. return this._submeshesOctree;
  18225. };
  18226. // Collisions
  18227. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18228. this._generatePointsArray();
  18229. if (!this._positions) {
  18230. return this;
  18231. }
  18232. // Transformation
  18233. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18234. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18235. subMesh._lastColliderWorldVertices = [];
  18236. subMesh._trianglePlanes = [];
  18237. var start = subMesh.verticesStart;
  18238. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18239. for (var i = start; i < end; i++) {
  18240. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18241. }
  18242. }
  18243. // Collide
  18244. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18245. if (collider.collisionFound) {
  18246. collider.collidedMesh = this;
  18247. }
  18248. return this;
  18249. };
  18250. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18251. var subMeshes;
  18252. var len;
  18253. // Octrees
  18254. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18255. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18256. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18257. len = intersections.length;
  18258. subMeshes = intersections.data;
  18259. }
  18260. else {
  18261. subMeshes = this.subMeshes;
  18262. len = subMeshes.length;
  18263. }
  18264. for (var index = 0; index < len; index++) {
  18265. var subMesh = subMeshes[index];
  18266. // Bounding test
  18267. if (len > 1 && !subMesh._checkCollision(collider))
  18268. continue;
  18269. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18270. }
  18271. return this;
  18272. };
  18273. AbstractMesh.prototype._checkCollision = function (collider) {
  18274. // Bounding box test
  18275. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18276. return this;
  18277. // Transformation matrix
  18278. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18279. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18280. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18281. return this;
  18282. };
  18283. // Picking
  18284. AbstractMesh.prototype._generatePointsArray = function () {
  18285. return false;
  18286. };
  18287. /**
  18288. * Checks if the passed Ray intersects with the mesh.
  18289. * Returns an object PickingInfo.
  18290. */
  18291. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18292. var pickingInfo = new BABYLON.PickingInfo();
  18293. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18294. return pickingInfo;
  18295. }
  18296. if (!this._generatePointsArray()) {
  18297. return pickingInfo;
  18298. }
  18299. var intersectInfo = null;
  18300. // Octrees
  18301. var subMeshes;
  18302. var len;
  18303. if (this._submeshesOctree && this.useOctreeForPicking) {
  18304. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18305. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18306. len = intersections.length;
  18307. subMeshes = intersections.data;
  18308. }
  18309. else {
  18310. subMeshes = this.subMeshes;
  18311. len = subMeshes.length;
  18312. }
  18313. for (var index = 0; index < len; index++) {
  18314. var subMesh = subMeshes[index];
  18315. // Bounding test
  18316. if (len > 1 && !subMesh.canIntersects(ray))
  18317. continue;
  18318. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18319. if (currentIntersectInfo) {
  18320. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18321. intersectInfo = currentIntersectInfo;
  18322. intersectInfo.subMeshId = index;
  18323. if (fastCheck) {
  18324. break;
  18325. }
  18326. }
  18327. }
  18328. }
  18329. if (intersectInfo) {
  18330. // Get picked point
  18331. var world = this.getWorldMatrix();
  18332. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18333. var direction = ray.direction.clone();
  18334. direction = direction.scale(intersectInfo.distance);
  18335. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18336. var pickedPoint = worldOrigin.add(worldDirection);
  18337. // Return result
  18338. pickingInfo.hit = true;
  18339. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18340. pickingInfo.pickedPoint = pickedPoint;
  18341. pickingInfo.pickedMesh = this;
  18342. pickingInfo.bu = intersectInfo.bu || 0;
  18343. pickingInfo.bv = intersectInfo.bv || 0;
  18344. pickingInfo.faceId = intersectInfo.faceId;
  18345. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18346. return pickingInfo;
  18347. }
  18348. return pickingInfo;
  18349. };
  18350. /**
  18351. * Clones the mesh, used by the class Mesh.
  18352. * Just returns `null` for an AbstractMesh.
  18353. */
  18354. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18355. return null;
  18356. };
  18357. /**
  18358. * Disposes all the mesh submeshes.
  18359. * Returns the AbstractMesh.
  18360. */
  18361. AbstractMesh.prototype.releaseSubMeshes = function () {
  18362. if (this.subMeshes) {
  18363. while (this.subMeshes.length) {
  18364. this.subMeshes[0].dispose();
  18365. }
  18366. }
  18367. else {
  18368. this.subMeshes = new Array();
  18369. }
  18370. return this;
  18371. };
  18372. /**
  18373. * Disposes the AbstractMesh.
  18374. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18375. * Returns nothing.
  18376. */
  18377. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18378. var _this = this;
  18379. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18380. var index;
  18381. // Action manager
  18382. if (this.actionManager !== undefined && this.actionManager !== null) {
  18383. this.actionManager.dispose();
  18384. this.actionManager = null;
  18385. }
  18386. // Skeleton
  18387. this.skeleton = null;
  18388. // Physics
  18389. if (this.physicsImpostor) {
  18390. this.physicsImpostor.dispose();
  18391. }
  18392. // Intersections in progress
  18393. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18394. var other = this._intersectionsInProgress[index];
  18395. var pos = other._intersectionsInProgress.indexOf(this);
  18396. other._intersectionsInProgress.splice(pos, 1);
  18397. }
  18398. this._intersectionsInProgress = [];
  18399. // Lights
  18400. var lights = this.getScene().lights;
  18401. lights.forEach(function (light) {
  18402. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18403. if (meshIndex !== -1) {
  18404. light.includedOnlyMeshes.splice(meshIndex, 1);
  18405. }
  18406. meshIndex = light.excludedMeshes.indexOf(_this);
  18407. if (meshIndex !== -1) {
  18408. light.excludedMeshes.splice(meshIndex, 1);
  18409. }
  18410. // Shadow generators
  18411. var generator = light.getShadowGenerator();
  18412. if (generator) {
  18413. var shadowMap = generator.getShadowMap();
  18414. if (shadowMap && shadowMap.renderList) {
  18415. meshIndex = shadowMap.renderList.indexOf(_this);
  18416. if (meshIndex !== -1) {
  18417. shadowMap.renderList.splice(meshIndex, 1);
  18418. }
  18419. }
  18420. }
  18421. });
  18422. // Edges
  18423. if (this._edgesRenderer) {
  18424. this._edgesRenderer.dispose();
  18425. this._edgesRenderer = null;
  18426. }
  18427. // SubMeshes
  18428. if (this.getClassName() !== "InstancedMesh") {
  18429. this.releaseSubMeshes();
  18430. }
  18431. // Octree
  18432. var sceneOctree = this.getScene().selectionOctree;
  18433. if (sceneOctree !== undefined && sceneOctree !== null) {
  18434. var index = sceneOctree.dynamicContent.indexOf(this);
  18435. if (index !== -1) {
  18436. sceneOctree.dynamicContent.splice(index, 1);
  18437. }
  18438. }
  18439. // Query
  18440. var engine = this.getScene().getEngine();
  18441. if (this._occlusionQuery) {
  18442. this._isOcclusionQueryInProgress = false;
  18443. engine.deleteQuery(this._occlusionQuery);
  18444. this._occlusionQuery = null;
  18445. }
  18446. // Engine
  18447. engine.wipeCaches();
  18448. // Remove from scene
  18449. this.getScene().removeMesh(this);
  18450. if (disposeMaterialAndTextures) {
  18451. if (this.material) {
  18452. this.material.dispose(false, true);
  18453. }
  18454. }
  18455. if (!doNotRecurse) {
  18456. // Particles
  18457. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18458. if (this.getScene().particleSystems[index].emitter === this) {
  18459. this.getScene().particleSystems[index].dispose();
  18460. index--;
  18461. }
  18462. }
  18463. }
  18464. // facet data
  18465. if (this._facetDataEnabled) {
  18466. this.disableFacetData();
  18467. }
  18468. this.onAfterWorldMatrixUpdateObservable.clear();
  18469. this.onCollideObservable.clear();
  18470. this.onCollisionPositionChangeObservable.clear();
  18471. _super.prototype.dispose.call(this, doNotRecurse);
  18472. };
  18473. /**
  18474. * Adds the passed mesh as a child to the current mesh.
  18475. * Returns the AbstractMesh.
  18476. */
  18477. AbstractMesh.prototype.addChild = function (mesh) {
  18478. mesh.setParent(this);
  18479. return this;
  18480. };
  18481. /**
  18482. * Removes the passed mesh from the current mesh children list.
  18483. * Returns the AbstractMesh.
  18484. */
  18485. AbstractMesh.prototype.removeChild = function (mesh) {
  18486. mesh.setParent(null);
  18487. return this;
  18488. };
  18489. // Facet data
  18490. /**
  18491. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18492. * Returns the AbstractMesh.
  18493. */
  18494. AbstractMesh.prototype._initFacetData = function () {
  18495. if (!this._facetNormals) {
  18496. this._facetNormals = new Array();
  18497. }
  18498. if (!this._facetPositions) {
  18499. this._facetPositions = new Array();
  18500. }
  18501. if (!this._facetPartitioning) {
  18502. this._facetPartitioning = new Array();
  18503. }
  18504. this._facetNb = (this.getIndices().length / 3) | 0;
  18505. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18506. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18507. for (var f = 0; f < this._facetNb; f++) {
  18508. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18509. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18510. }
  18511. this._facetDataEnabled = true;
  18512. return this;
  18513. };
  18514. /**
  18515. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18516. * This method can be called within the render loop.
  18517. * 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.
  18518. * Returns the AbstractMesh.
  18519. */
  18520. AbstractMesh.prototype.updateFacetData = function () {
  18521. if (!this._facetDataEnabled) {
  18522. this._initFacetData();
  18523. }
  18524. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18525. var indices = this.getIndices();
  18526. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18527. var bInfo = this.getBoundingInfo();
  18528. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18529. // init arrays, matrix and sort function on first call
  18530. this._facetDepthSortEnabled = true;
  18531. if (indices instanceof Uint16Array) {
  18532. this._depthSortedIndices = new Uint16Array(indices);
  18533. }
  18534. else if (indices instanceof Uint32Array) {
  18535. this._depthSortedIndices = new Uint32Array(indices);
  18536. }
  18537. else {
  18538. var needs32bits = false;
  18539. for (var i = 0; i < indices.length; i++) {
  18540. if (indices[i] > 65535) {
  18541. needs32bits = true;
  18542. break;
  18543. }
  18544. }
  18545. if (needs32bits) {
  18546. this._depthSortedIndices = new Uint32Array(indices);
  18547. }
  18548. else {
  18549. this._depthSortedIndices = new Uint16Array(indices);
  18550. }
  18551. }
  18552. this._facetDepthSortFunction = function (f1, f2) {
  18553. return (f2.sqDistance - f1.sqDistance);
  18554. };
  18555. if (!this._facetDepthSortFrom) {
  18556. var camera = this.getScene().activeCamera;
  18557. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18558. }
  18559. this._depthSortedFacets = [];
  18560. for (var f = 0; f < this._facetNb; f++) {
  18561. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18562. this._depthSortedFacets.push(depthSortedFacet);
  18563. }
  18564. this._invertedMatrix = BABYLON.Matrix.Identity();
  18565. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18566. }
  18567. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18568. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18569. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18570. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18571. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18572. this._subDiv.max = this._partitioningSubdivisions;
  18573. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18574. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18575. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18576. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18577. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18578. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18579. // set the parameters for ComputeNormals()
  18580. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18581. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18582. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18583. this._facetParameters.bInfo = bInfo;
  18584. this._facetParameters.bbSize = this._bbSize;
  18585. this._facetParameters.subDiv = this._subDiv;
  18586. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18587. this._facetParameters.depthSort = this._facetDepthSort;
  18588. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18589. this.computeWorldMatrix(true);
  18590. this._worldMatrix.invertToRef(this._invertedMatrix);
  18591. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18592. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18593. }
  18594. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18595. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18596. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18597. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18598. var l = (this._depthSortedIndices.length / 3) | 0;
  18599. for (var f = 0; f < l; f++) {
  18600. var sind = this._depthSortedFacets[f].ind;
  18601. this._depthSortedIndices[f * 3] = indices[sind];
  18602. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18603. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18604. }
  18605. this.updateIndices(this._depthSortedIndices);
  18606. }
  18607. return this;
  18608. };
  18609. /**
  18610. * Returns the facetLocalNormals array.
  18611. * The normals are expressed in the mesh local space.
  18612. */
  18613. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18614. if (!this._facetNormals) {
  18615. this.updateFacetData();
  18616. }
  18617. return this._facetNormals;
  18618. };
  18619. /**
  18620. * Returns the facetLocalPositions array.
  18621. * The facet positions are expressed in the mesh local space.
  18622. */
  18623. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18624. if (!this._facetPositions) {
  18625. this.updateFacetData();
  18626. }
  18627. return this._facetPositions;
  18628. };
  18629. /**
  18630. * Returns the facetLocalPartioning array.
  18631. */
  18632. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18633. if (!this._facetPartitioning) {
  18634. this.updateFacetData();
  18635. }
  18636. return this._facetPartitioning;
  18637. };
  18638. /**
  18639. * Returns the i-th facet position in the world system.
  18640. * This method allocates a new Vector3 per call.
  18641. */
  18642. AbstractMesh.prototype.getFacetPosition = function (i) {
  18643. var pos = BABYLON.Vector3.Zero();
  18644. this.getFacetPositionToRef(i, pos);
  18645. return pos;
  18646. };
  18647. /**
  18648. * Sets the reference Vector3 with the i-th facet position in the world system.
  18649. * Returns the AbstractMesh.
  18650. */
  18651. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18652. var localPos = (this.getFacetLocalPositions())[i];
  18653. var world = this.getWorldMatrix();
  18654. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18655. return this;
  18656. };
  18657. /**
  18658. * Returns the i-th facet normal in the world system.
  18659. * This method allocates a new Vector3 per call.
  18660. */
  18661. AbstractMesh.prototype.getFacetNormal = function (i) {
  18662. var norm = BABYLON.Vector3.Zero();
  18663. this.getFacetNormalToRef(i, norm);
  18664. return norm;
  18665. };
  18666. /**
  18667. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18668. * Returns the AbstractMesh.
  18669. */
  18670. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18671. var localNorm = (this.getFacetLocalNormals())[i];
  18672. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18673. return this;
  18674. };
  18675. /**
  18676. * 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).
  18677. */
  18678. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18679. var bInfo = this.getBoundingInfo();
  18680. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18681. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18682. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18683. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18684. return null;
  18685. }
  18686. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18687. };
  18688. /**
  18689. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18690. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18691. * If checkFace is 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.
  18692. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18693. * 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.
  18694. */
  18695. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18696. if (checkFace === void 0) { checkFace = false; }
  18697. if (facing === void 0) { facing = true; }
  18698. var world = this.getWorldMatrix();
  18699. var invMat = BABYLON.Tmp.Matrix[5];
  18700. world.invertToRef(invMat);
  18701. var invVect = BABYLON.Tmp.Vector3[8];
  18702. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18703. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18704. if (projected) {
  18705. // tranform the local computed projected vector to world coordinates
  18706. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18707. }
  18708. return closest;
  18709. };
  18710. /**
  18711. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18712. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18713. * If checkFace is 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.
  18714. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18715. * 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.
  18716. */
  18717. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18718. if (checkFace === void 0) { checkFace = false; }
  18719. if (facing === void 0) { facing = true; }
  18720. var closest = null;
  18721. var tmpx = 0.0;
  18722. var tmpy = 0.0;
  18723. var tmpz = 0.0;
  18724. var d = 0.0; // tmp dot facet normal * facet position
  18725. var t0 = 0.0;
  18726. var projx = 0.0;
  18727. var projy = 0.0;
  18728. var projz = 0.0;
  18729. // Get all the facets in the same partitioning block than (x, y, z)
  18730. var facetPositions = this.getFacetLocalPositions();
  18731. var facetNormals = this.getFacetLocalNormals();
  18732. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18733. if (!facetsInBlock) {
  18734. return null;
  18735. }
  18736. // Get the closest facet to (x, y, z)
  18737. var shortest = Number.MAX_VALUE; // init distance vars
  18738. var tmpDistance = shortest;
  18739. var fib; // current facet in the block
  18740. var norm; // current facet normal
  18741. var p0; // current facet barycenter position
  18742. // loop on all the facets in the current partitioning block
  18743. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18744. fib = facetsInBlock[idx];
  18745. norm = facetNormals[fib];
  18746. p0 = facetPositions[fib];
  18747. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18748. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18749. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18750. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18751. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18752. projx = x + norm.x * t0;
  18753. projy = y + norm.y * t0;
  18754. projz = z + norm.z * t0;
  18755. tmpx = projx - x;
  18756. tmpy = projy - y;
  18757. tmpz = projz - z;
  18758. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18759. if (tmpDistance < shortest) {
  18760. shortest = tmpDistance;
  18761. closest = fib;
  18762. if (projected) {
  18763. projected.x = projx;
  18764. projected.y = projy;
  18765. projected.z = projz;
  18766. }
  18767. }
  18768. }
  18769. }
  18770. return closest;
  18771. };
  18772. /**
  18773. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18774. */
  18775. AbstractMesh.prototype.getFacetDataParameters = function () {
  18776. return this._facetParameters;
  18777. };
  18778. /**
  18779. * Disables the feature FacetData and frees the related memory.
  18780. * Returns the AbstractMesh.
  18781. */
  18782. AbstractMesh.prototype.disableFacetData = function () {
  18783. if (this._facetDataEnabled) {
  18784. this._facetDataEnabled = false;
  18785. this._facetPositions = new Array();
  18786. this._facetNormals = new Array();
  18787. this._facetPartitioning = new Array();
  18788. this._facetParameters = null;
  18789. this._depthSortedIndices = new Uint32Array(0);
  18790. }
  18791. return this;
  18792. };
  18793. /**
  18794. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18795. * Returns the mesh.
  18796. */
  18797. AbstractMesh.prototype.updateIndices = function (indices) {
  18798. return this;
  18799. };
  18800. /**
  18801. * The mesh Geometry. Actually used by the Mesh object.
  18802. * Returns a blank geometry object.
  18803. */
  18804. /**
  18805. * Creates new normals data for the mesh.
  18806. * @param updatable.
  18807. */
  18808. AbstractMesh.prototype.createNormals = function (updatable) {
  18809. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18810. var indices = this.getIndices();
  18811. var normals;
  18812. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18813. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18814. }
  18815. else {
  18816. normals = [];
  18817. }
  18818. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18819. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18820. };
  18821. /**
  18822. * Align the mesh with a normal.
  18823. * Returns the mesh.
  18824. */
  18825. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18826. if (!upDirection) {
  18827. upDirection = BABYLON.Axis.Y;
  18828. }
  18829. var axisX = BABYLON.Tmp.Vector3[0];
  18830. var axisZ = BABYLON.Tmp.Vector3[1];
  18831. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18832. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18833. if (this.rotationQuaternion) {
  18834. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18835. }
  18836. else {
  18837. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18838. }
  18839. return this;
  18840. };
  18841. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18842. var engine = this.getEngine();
  18843. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18844. this._isOccluded = false;
  18845. return;
  18846. }
  18847. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18848. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18849. if (isOcclusionQueryAvailable) {
  18850. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18851. this._isOcclusionQueryInProgress = false;
  18852. this._occlusionInternalRetryCounter = 0;
  18853. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18854. }
  18855. else {
  18856. this._occlusionInternalRetryCounter++;
  18857. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18858. this._isOcclusionQueryInProgress = false;
  18859. this._occlusionInternalRetryCounter = 0;
  18860. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18861. // if strict continue the last state of the object.
  18862. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18863. }
  18864. else {
  18865. return;
  18866. }
  18867. }
  18868. }
  18869. var scene = this.getScene();
  18870. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18871. if (!this._occlusionQuery) {
  18872. this._occlusionQuery = engine.createQuery();
  18873. }
  18874. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18875. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18876. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18877. this._isOcclusionQueryInProgress = true;
  18878. };
  18879. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18880. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18881. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18882. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18883. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18884. return AbstractMesh;
  18885. }(BABYLON.TransformNode));
  18886. BABYLON.AbstractMesh = AbstractMesh;
  18887. })(BABYLON || (BABYLON = {}));
  18888. //# sourceMappingURL=babylon.abstractMesh.js.map
  18889. var BABYLON;
  18890. (function (BABYLON) {
  18891. /**
  18892. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18893. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18894. * 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.
  18895. */
  18896. var Light = /** @class */ (function (_super) {
  18897. __extends(Light, _super);
  18898. /**
  18899. * Creates a Light object in the scene.
  18900. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18901. * @param name The firendly name of the light
  18902. * @param scene The scene the light belongs too
  18903. */
  18904. function Light(name, scene) {
  18905. var _this = _super.call(this, name, scene) || this;
  18906. /**
  18907. * Diffuse gives the basic color to an object.
  18908. */
  18909. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18910. /**
  18911. * Specular produces a highlight color on an object.
  18912. * Note: This is note affecting PBR materials.
  18913. */
  18914. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18915. /**
  18916. * Strength of the light.
  18917. * Note: By default it is define in the framework own unit.
  18918. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18919. */
  18920. _this.intensity = 1.0;
  18921. /**
  18922. * Defines how far from the source the light is impacting in scene units.
  18923. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18924. */
  18925. _this.range = Number.MAX_VALUE;
  18926. /**
  18927. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18928. * of light.
  18929. */
  18930. _this._photometricScale = 1.0;
  18931. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18932. _this._radius = 0.00001;
  18933. /**
  18934. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18935. * exceeding the number allowed of the materials.
  18936. */
  18937. _this.renderPriority = 0;
  18938. /**
  18939. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18940. * the current shadow generator.
  18941. */
  18942. _this.shadowEnabled = true;
  18943. _this._excludeWithLayerMask = 0;
  18944. _this._includeOnlyWithLayerMask = 0;
  18945. _this._lightmapMode = 0;
  18946. /**
  18947. * @ignore Internal use only.
  18948. */
  18949. _this._excludedMeshesIds = new Array();
  18950. /**
  18951. * @ignore Internal use only.
  18952. */
  18953. _this._includedOnlyMeshesIds = new Array();
  18954. _this.getScene().addLight(_this);
  18955. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18956. _this._buildUniformLayout();
  18957. _this.includedOnlyMeshes = new Array();
  18958. _this.excludedMeshes = new Array();
  18959. _this._resyncMeshes();
  18960. return _this;
  18961. }
  18962. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18963. /**
  18964. * If every light affecting the material is in this lightmapMode,
  18965. * material.lightmapTexture adds or multiplies
  18966. * (depends on material.useLightmapAsShadowmap)
  18967. * after every other light calculations.
  18968. */
  18969. get: function () {
  18970. return Light._LIGHTMAP_DEFAULT;
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18976. /**
  18977. * material.lightmapTexture as only diffuse lighting from this light
  18978. * adds only specular lighting from this light
  18979. * adds dynamic shadows
  18980. */
  18981. get: function () {
  18982. return Light._LIGHTMAP_SPECULAR;
  18983. },
  18984. enumerable: true,
  18985. configurable: true
  18986. });
  18987. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18988. /**
  18989. * material.lightmapTexture as only lighting
  18990. * no light calculation from this light
  18991. * only adds dynamic shadows from this light
  18992. */
  18993. get: function () {
  18994. return Light._LIGHTMAP_SHADOWSONLY;
  18995. },
  18996. enumerable: true,
  18997. configurable: true
  18998. });
  18999. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19000. /**
  19001. * Each light type uses the default quantity according to its type:
  19002. * point/spot lights use luminous intensity
  19003. * directional lights use illuminance
  19004. */
  19005. get: function () {
  19006. return Light._INTENSITYMODE_AUTOMATIC;
  19007. },
  19008. enumerable: true,
  19009. configurable: true
  19010. });
  19011. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19012. /**
  19013. * lumen (lm)
  19014. */
  19015. get: function () {
  19016. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19017. },
  19018. enumerable: true,
  19019. configurable: true
  19020. });
  19021. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19022. /**
  19023. * candela (lm/sr)
  19024. */
  19025. get: function () {
  19026. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19032. /**
  19033. * lux (lm/m^2)
  19034. */
  19035. get: function () {
  19036. return Light._INTENSITYMODE_ILLUMINANCE;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19042. /**
  19043. * nit (cd/m^2)
  19044. */
  19045. get: function () {
  19046. return Light._INTENSITYMODE_LUMINANCE;
  19047. },
  19048. enumerable: true,
  19049. configurable: true
  19050. });
  19051. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19052. /**
  19053. * Light type const id of the point light.
  19054. */
  19055. get: function () {
  19056. return Light._LIGHTTYPEID_POINTLIGHT;
  19057. },
  19058. enumerable: true,
  19059. configurable: true
  19060. });
  19061. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19062. /**
  19063. * Light type const id of the directional light.
  19064. */
  19065. get: function () {
  19066. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19072. /**
  19073. * Light type const id of the spot light.
  19074. */
  19075. get: function () {
  19076. return Light._LIGHTTYPEID_SPOTLIGHT;
  19077. },
  19078. enumerable: true,
  19079. configurable: true
  19080. });
  19081. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19082. /**
  19083. * Light type const id of the hemispheric light.
  19084. */
  19085. get: function () {
  19086. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Light.prototype, "intensityMode", {
  19092. /**
  19093. * Gets the photometric scale used to interpret the intensity.
  19094. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19095. */
  19096. get: function () {
  19097. return this._intensityMode;
  19098. },
  19099. /**
  19100. * Sets the photometric scale used to interpret the intensity.
  19101. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19102. */
  19103. set: function (value) {
  19104. this._intensityMode = value;
  19105. this._computePhotometricScale();
  19106. },
  19107. enumerable: true,
  19108. configurable: true
  19109. });
  19110. ;
  19111. ;
  19112. Object.defineProperty(Light.prototype, "radius", {
  19113. /**
  19114. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19115. */
  19116. get: function () {
  19117. return this._radius;
  19118. },
  19119. /**
  19120. * sets the light radius used by PBR Materials to simulate soft area lights.
  19121. */
  19122. set: function (value) {
  19123. this._radius = value;
  19124. this._computePhotometricScale();
  19125. },
  19126. enumerable: true,
  19127. configurable: true
  19128. });
  19129. ;
  19130. ;
  19131. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19132. /**
  19133. * Gets the only meshes impacted by this light.
  19134. */
  19135. get: function () {
  19136. return this._includedOnlyMeshes;
  19137. },
  19138. /**
  19139. * Sets the only meshes impacted by this light.
  19140. */
  19141. set: function (value) {
  19142. this._includedOnlyMeshes = value;
  19143. this._hookArrayForIncludedOnly(value);
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19149. /**
  19150. * Gets the meshes not impacted by this light.
  19151. */
  19152. get: function () {
  19153. return this._excludedMeshes;
  19154. },
  19155. /**
  19156. * Sets the meshes not impacted by this light.
  19157. */
  19158. set: function (value) {
  19159. this._excludedMeshes = value;
  19160. this._hookArrayForExcluded(value);
  19161. },
  19162. enumerable: true,
  19163. configurable: true
  19164. });
  19165. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19166. /**
  19167. * Gets the layer id use to find what meshes are not impacted by the light.
  19168. * Inactive if 0
  19169. */
  19170. get: function () {
  19171. return this._excludeWithLayerMask;
  19172. },
  19173. /**
  19174. * Sets the layer id use to find what meshes are not impacted by the light.
  19175. * Inactive if 0
  19176. */
  19177. set: function (value) {
  19178. this._excludeWithLayerMask = value;
  19179. this._resyncMeshes();
  19180. },
  19181. enumerable: true,
  19182. configurable: true
  19183. });
  19184. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19185. /**
  19186. * Gets the layer id use to find what meshes are impacted by the light.
  19187. * Inactive if 0
  19188. */
  19189. get: function () {
  19190. return this._includeOnlyWithLayerMask;
  19191. },
  19192. /**
  19193. * Sets the layer id use to find what meshes are impacted by the light.
  19194. * Inactive if 0
  19195. */
  19196. set: function (value) {
  19197. this._includeOnlyWithLayerMask = value;
  19198. this._resyncMeshes();
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. Object.defineProperty(Light.prototype, "lightmapMode", {
  19204. /**
  19205. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19206. */
  19207. get: function () {
  19208. return this._lightmapMode;
  19209. },
  19210. /**
  19211. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19212. */
  19213. set: function (value) {
  19214. if (this._lightmapMode === value) {
  19215. return;
  19216. }
  19217. this._lightmapMode = value;
  19218. this._markMeshesAsLightDirty();
  19219. },
  19220. enumerable: true,
  19221. configurable: true
  19222. });
  19223. /**
  19224. * Returns the string "Light".
  19225. * @returns the class name
  19226. */
  19227. Light.prototype.getClassName = function () {
  19228. return "Light";
  19229. };
  19230. /**
  19231. * Converts the light information to a readable string for debug purpose.
  19232. * @param fullDetails Supports for multiple levels of logging within scene loading
  19233. * @returns the human readable light info
  19234. */
  19235. Light.prototype.toString = function (fullDetails) {
  19236. var ret = "Name: " + this.name;
  19237. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19238. if (this.animations) {
  19239. for (var i = 0; i < this.animations.length; i++) {
  19240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19241. }
  19242. }
  19243. if (fullDetails) {
  19244. }
  19245. return ret;
  19246. };
  19247. /**
  19248. * Set the enabled state of this node.
  19249. * @param value - the new enabled state
  19250. * @see isEnabled
  19251. */
  19252. Light.prototype.setEnabled = function (value) {
  19253. _super.prototype.setEnabled.call(this, value);
  19254. this._resyncMeshes();
  19255. };
  19256. /**
  19257. * Returns the Light associated shadow generator if any.
  19258. * @return the associated shadow generator.
  19259. */
  19260. Light.prototype.getShadowGenerator = function () {
  19261. return this._shadowGenerator;
  19262. };
  19263. /**
  19264. * Returns a Vector3, the absolute light position in the World.
  19265. * @returns the world space position of the light
  19266. */
  19267. Light.prototype.getAbsolutePosition = function () {
  19268. return BABYLON.Vector3.Zero();
  19269. };
  19270. /**
  19271. * Specifies if the light will affect the passed mesh.
  19272. * @param mesh The mesh to test against the light
  19273. * @return true the mesh is affected otherwise, false.
  19274. */
  19275. Light.prototype.canAffectMesh = function (mesh) {
  19276. if (!mesh) {
  19277. return true;
  19278. }
  19279. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19280. return false;
  19281. }
  19282. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19283. return false;
  19284. }
  19285. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19286. return false;
  19287. }
  19288. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19289. return false;
  19290. }
  19291. return true;
  19292. };
  19293. /**
  19294. * Computes and Returns the light World matrix.
  19295. * @returns the world matrix
  19296. */
  19297. Light.prototype.getWorldMatrix = function () {
  19298. this._currentRenderId = this.getScene().getRenderId();
  19299. var worldMatrix = this._getWorldMatrix();
  19300. if (this.parent && this.parent.getWorldMatrix) {
  19301. if (!this._parentedWorldMatrix) {
  19302. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19303. }
  19304. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19305. this._markSyncedWithParent();
  19306. return this._parentedWorldMatrix;
  19307. }
  19308. return worldMatrix;
  19309. };
  19310. /**
  19311. * Sort function to order lights for rendering.
  19312. * @param a First Light object to compare to second.
  19313. * @param b Second Light object to compare first.
  19314. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19315. */
  19316. Light.CompareLightsPriority = function (a, b) {
  19317. //shadow-casting lights have priority over non-shadow-casting lights
  19318. //the renderPrioirty is a secondary sort criterion
  19319. if (a.shadowEnabled !== b.shadowEnabled) {
  19320. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19321. }
  19322. return b.renderPriority - a.renderPriority;
  19323. };
  19324. /**
  19325. * Disposes the light.
  19326. */
  19327. Light.prototype.dispose = function () {
  19328. if (this._shadowGenerator) {
  19329. this._shadowGenerator.dispose();
  19330. this._shadowGenerator = null;
  19331. }
  19332. // Animations
  19333. this.getScene().stopAnimation(this);
  19334. // Remove from meshes
  19335. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19336. var mesh = _a[_i];
  19337. mesh._removeLightSource(this);
  19338. }
  19339. this._uniformBuffer.dispose();
  19340. // Remove from scene
  19341. this.getScene().removeLight(this);
  19342. _super.prototype.dispose.call(this);
  19343. };
  19344. /**
  19345. * Returns the light type ID (integer).
  19346. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19347. */
  19348. Light.prototype.getTypeID = function () {
  19349. return 0;
  19350. };
  19351. /**
  19352. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19353. * @returns the scaled intensity in intensity mode unit
  19354. */
  19355. Light.prototype.getScaledIntensity = function () {
  19356. return this._photometricScale * this.intensity;
  19357. };
  19358. /**
  19359. * Returns a new Light object, named "name", from the current one.
  19360. * @param name The name of the cloned light
  19361. * @returns the new created light
  19362. */
  19363. Light.prototype.clone = function (name) {
  19364. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19365. if (!constructor) {
  19366. return null;
  19367. }
  19368. return BABYLON.SerializationHelper.Clone(constructor, this);
  19369. };
  19370. /**
  19371. * Serializes the current light into a Serialization object.
  19372. * @returns the serialized object.
  19373. */
  19374. Light.prototype.serialize = function () {
  19375. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19376. // Type
  19377. serializationObject.type = this.getTypeID();
  19378. // Parent
  19379. if (this.parent) {
  19380. serializationObject.parentId = this.parent.id;
  19381. }
  19382. // Inclusion / exclusions
  19383. if (this.excludedMeshes.length > 0) {
  19384. serializationObject.excludedMeshesIds = [];
  19385. this.excludedMeshes.forEach(function (mesh) {
  19386. serializationObject.excludedMeshesIds.push(mesh.id);
  19387. });
  19388. }
  19389. if (this.includedOnlyMeshes.length > 0) {
  19390. serializationObject.includedOnlyMeshesIds = [];
  19391. this.includedOnlyMeshes.forEach(function (mesh) {
  19392. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19393. });
  19394. }
  19395. // Animations
  19396. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19397. serializationObject.ranges = this.serializeAnimationRanges();
  19398. return serializationObject;
  19399. };
  19400. /**
  19401. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19402. * This new light is named "name" and added to the passed scene.
  19403. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19404. * @param name The friendly name of the light
  19405. * @param scene The scene the new light will belong to
  19406. * @returns the constructor function
  19407. */
  19408. Light.GetConstructorFromName = function (type, name, scene) {
  19409. switch (type) {
  19410. case 0:
  19411. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19412. case 1:
  19413. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19414. case 2:
  19415. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19416. case 3:
  19417. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19418. }
  19419. return null;
  19420. };
  19421. /**
  19422. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19423. * @param parsedLight The JSON representation of the light
  19424. * @param scene The scene to create the parsed light in
  19425. * @returns the created light after parsing
  19426. */
  19427. Light.Parse = function (parsedLight, scene) {
  19428. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19429. if (!constructor) {
  19430. return null;
  19431. }
  19432. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19433. // Inclusion / exclusions
  19434. if (parsedLight.excludedMeshesIds) {
  19435. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19436. }
  19437. if (parsedLight.includedOnlyMeshesIds) {
  19438. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19439. }
  19440. // Parent
  19441. if (parsedLight.parentId) {
  19442. light._waitingParentId = parsedLight.parentId;
  19443. }
  19444. // Animations
  19445. if (parsedLight.animations) {
  19446. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19447. var parsedAnimation = parsedLight.animations[animationIndex];
  19448. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19449. }
  19450. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19451. }
  19452. if (parsedLight.autoAnimate) {
  19453. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19454. }
  19455. return light;
  19456. };
  19457. Light.prototype._hookArrayForExcluded = function (array) {
  19458. var _this = this;
  19459. var oldPush = array.push;
  19460. array.push = function () {
  19461. var items = [];
  19462. for (var _i = 0; _i < arguments.length; _i++) {
  19463. items[_i] = arguments[_i];
  19464. }
  19465. var result = oldPush.apply(array, items);
  19466. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19467. var item = items_1[_a];
  19468. item._resyncLighSource(_this);
  19469. }
  19470. return result;
  19471. };
  19472. var oldSplice = array.splice;
  19473. array.splice = function (index, deleteCount) {
  19474. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19475. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19476. var item = deleted_1[_i];
  19477. item._resyncLighSource(_this);
  19478. }
  19479. return deleted;
  19480. };
  19481. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19482. var item = array_1[_i];
  19483. item._resyncLighSource(this);
  19484. }
  19485. };
  19486. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19487. var _this = this;
  19488. var oldPush = array.push;
  19489. array.push = function () {
  19490. var items = [];
  19491. for (var _i = 0; _i < arguments.length; _i++) {
  19492. items[_i] = arguments[_i];
  19493. }
  19494. var result = oldPush.apply(array, items);
  19495. _this._resyncMeshes();
  19496. return result;
  19497. };
  19498. var oldSplice = array.splice;
  19499. array.splice = function (index, deleteCount) {
  19500. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19501. _this._resyncMeshes();
  19502. return deleted;
  19503. };
  19504. this._resyncMeshes();
  19505. };
  19506. Light.prototype._resyncMeshes = function () {
  19507. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19508. var mesh = _a[_i];
  19509. mesh._resyncLighSource(this);
  19510. }
  19511. };
  19512. /**
  19513. * Forces the meshes to update their light related information in their rendering used effects
  19514. * @ignore Internal Use Only
  19515. */
  19516. Light.prototype._markMeshesAsLightDirty = function () {
  19517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19518. var mesh = _a[_i];
  19519. if (mesh._lightSources.indexOf(this) !== -1) {
  19520. mesh._markSubMeshesAsLightDirty();
  19521. }
  19522. }
  19523. };
  19524. /**
  19525. * Recomputes the cached photometric scale if needed.
  19526. */
  19527. Light.prototype._computePhotometricScale = function () {
  19528. this._photometricScale = this._getPhotometricScale();
  19529. this.getScene().resetCachedMaterial();
  19530. };
  19531. /**
  19532. * Returns the Photometric Scale according to the light type and intensity mode.
  19533. */
  19534. Light.prototype._getPhotometricScale = function () {
  19535. var photometricScale = 0.0;
  19536. var lightTypeID = this.getTypeID();
  19537. //get photometric mode
  19538. var photometricMode = this.intensityMode;
  19539. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19540. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19541. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19542. }
  19543. else {
  19544. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19545. }
  19546. }
  19547. //compute photometric scale
  19548. switch (lightTypeID) {
  19549. case Light.LIGHTTYPEID_POINTLIGHT:
  19550. case Light.LIGHTTYPEID_SPOTLIGHT:
  19551. switch (photometricMode) {
  19552. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19553. photometricScale = 1.0 / (4.0 * Math.PI);
  19554. break;
  19555. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19556. photometricScale = 1.0;
  19557. break;
  19558. case Light.INTENSITYMODE_LUMINANCE:
  19559. photometricScale = this.radius * this.radius;
  19560. break;
  19561. }
  19562. break;
  19563. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19564. switch (photometricMode) {
  19565. case Light.INTENSITYMODE_ILLUMINANCE:
  19566. photometricScale = 1.0;
  19567. break;
  19568. case Light.INTENSITYMODE_LUMINANCE:
  19569. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19570. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19571. var apexAngleRadians = this.radius;
  19572. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19573. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19574. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19575. photometricScale = solidAngle;
  19576. break;
  19577. }
  19578. break;
  19579. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19580. // No fall off in hemisperic light.
  19581. photometricScale = 1.0;
  19582. break;
  19583. }
  19584. return photometricScale;
  19585. };
  19586. /**
  19587. * Reorder the light in the scene according to their defined priority.
  19588. * @ignore Internal Use Only
  19589. */
  19590. Light.prototype._reorderLightsInScene = function () {
  19591. var scene = this.getScene();
  19592. if (this._renderPriority != 0) {
  19593. scene.requireLightSorting = true;
  19594. }
  19595. this.getScene().sortLightsByPriority();
  19596. };
  19597. //lightmapMode Consts
  19598. Light._LIGHTMAP_DEFAULT = 0;
  19599. Light._LIGHTMAP_SPECULAR = 1;
  19600. Light._LIGHTMAP_SHADOWSONLY = 2;
  19601. // Intensity Mode Consts
  19602. Light._INTENSITYMODE_AUTOMATIC = 0;
  19603. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19604. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19605. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19606. Light._INTENSITYMODE_LUMINANCE = 4;
  19607. // Light types ids const.
  19608. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19609. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19610. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19611. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19612. __decorate([
  19613. BABYLON.serializeAsColor3()
  19614. ], Light.prototype, "diffuse", void 0);
  19615. __decorate([
  19616. BABYLON.serializeAsColor3()
  19617. ], Light.prototype, "specular", void 0);
  19618. __decorate([
  19619. BABYLON.serialize()
  19620. ], Light.prototype, "intensity", void 0);
  19621. __decorate([
  19622. BABYLON.serialize()
  19623. ], Light.prototype, "range", void 0);
  19624. __decorate([
  19625. BABYLON.serialize()
  19626. ], Light.prototype, "intensityMode", null);
  19627. __decorate([
  19628. BABYLON.serialize()
  19629. ], Light.prototype, "radius", null);
  19630. __decorate([
  19631. BABYLON.serialize()
  19632. ], Light.prototype, "_renderPriority", void 0);
  19633. __decorate([
  19634. BABYLON.expandToProperty("_reorderLightsInScene")
  19635. ], Light.prototype, "renderPriority", void 0);
  19636. __decorate([
  19637. BABYLON.serialize()
  19638. ], Light.prototype, "shadowEnabled", void 0);
  19639. __decorate([
  19640. BABYLON.serialize("excludeWithLayerMask")
  19641. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19642. __decorate([
  19643. BABYLON.serialize("includeOnlyWithLayerMask")
  19644. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19645. __decorate([
  19646. BABYLON.serialize("lightmapMode")
  19647. ], Light.prototype, "_lightmapMode", void 0);
  19648. return Light;
  19649. }(BABYLON.Node));
  19650. BABYLON.Light = Light;
  19651. })(BABYLON || (BABYLON = {}));
  19652. //# sourceMappingURL=babylon.light.js.map
  19653. var BABYLON;
  19654. (function (BABYLON) {
  19655. var Camera = /** @class */ (function (_super) {
  19656. __extends(Camera, _super);
  19657. function Camera(name, position, scene) {
  19658. var _this = _super.call(this, name, scene) || this;
  19659. /**
  19660. * The vector the camera should consider as up.
  19661. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19662. */
  19663. _this.upVector = BABYLON.Vector3.Up();
  19664. _this.orthoLeft = null;
  19665. _this.orthoRight = null;
  19666. _this.orthoBottom = null;
  19667. _this.orthoTop = null;
  19668. /**
  19669. * FOV is set in Radians. (default is 0.8)
  19670. */
  19671. _this.fov = 0.8;
  19672. _this.minZ = 1;
  19673. _this.maxZ = 10000.0;
  19674. _this.inertia = 0.9;
  19675. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19676. _this.isIntermediate = false;
  19677. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19678. /**
  19679. * Restricts the camera to viewing objects with the same layerMask.
  19680. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19681. */
  19682. _this.layerMask = 0x0FFFFFFF;
  19683. /**
  19684. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19685. */
  19686. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19687. // Camera rig members
  19688. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19689. _this._rigCameras = new Array();
  19690. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19691. _this._skipRendering = false;
  19692. _this.customRenderTargets = new Array();
  19693. // Observables
  19694. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19695. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19696. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19697. _this.onRestoreStateObservable = new BABYLON.Observable();
  19698. // Cache
  19699. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19700. _this._projectionMatrix = new BABYLON.Matrix();
  19701. _this._doNotComputeProjectionMatrix = false;
  19702. _this._postProcesses = new Array();
  19703. _this._transformMatrix = BABYLON.Matrix.Zero();
  19704. _this._activeMeshes = new BABYLON.SmartArray(256);
  19705. _this._globalPosition = BABYLON.Vector3.Zero();
  19706. _this._refreshFrustumPlanes = true;
  19707. _this.getScene().addCamera(_this);
  19708. if (!_this.getScene().activeCamera) {
  19709. _this.getScene().activeCamera = _this;
  19710. }
  19711. _this.position = position;
  19712. return _this;
  19713. }
  19714. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19715. get: function () {
  19716. return Camera._PERSPECTIVE_CAMERA;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19722. get: function () {
  19723. return Camera._ORTHOGRAPHIC_CAMERA;
  19724. },
  19725. enumerable: true,
  19726. configurable: true
  19727. });
  19728. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19729. /**
  19730. * This is the default FOV mode for perspective cameras.
  19731. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19732. *
  19733. */
  19734. get: function () {
  19735. return Camera._FOVMODE_VERTICAL_FIXED;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19741. /**
  19742. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19743. *
  19744. */
  19745. get: function () {
  19746. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19752. get: function () {
  19753. return Camera._RIG_MODE_NONE;
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19759. get: function () {
  19760. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19766. get: function () {
  19767. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19773. get: function () {
  19774. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19780. get: function () {
  19781. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19787. get: function () {
  19788. return Camera._RIG_MODE_VR;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19794. get: function () {
  19795. return Camera._RIG_MODE_WEBVR;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. /**
  19801. * Store current camera state (fov, position, etc..)
  19802. */
  19803. Camera.prototype.storeState = function () {
  19804. this._stateStored = true;
  19805. this._storedFov = this.fov;
  19806. return this;
  19807. };
  19808. /**
  19809. * Restores the camera state values if it has been stored. You must call storeState() first
  19810. */
  19811. Camera.prototype._restoreStateValues = function () {
  19812. if (!this._stateStored) {
  19813. return false;
  19814. }
  19815. this.fov = this._storedFov;
  19816. return true;
  19817. };
  19818. /**
  19819. * Restored camera state. You must call storeState() first
  19820. */
  19821. Camera.prototype.restoreState = function () {
  19822. if (this._restoreStateValues()) {
  19823. this.onRestoreStateObservable.notifyObservers(this);
  19824. return true;
  19825. }
  19826. return false;
  19827. };
  19828. Camera.prototype.getClassName = function () {
  19829. return "Camera";
  19830. };
  19831. /**
  19832. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19833. */
  19834. Camera.prototype.toString = function (fullDetails) {
  19835. var ret = "Name: " + this.name;
  19836. ret += ", type: " + this.getClassName();
  19837. if (this.animations) {
  19838. for (var i = 0; i < this.animations.length; i++) {
  19839. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19840. }
  19841. }
  19842. if (fullDetails) {
  19843. }
  19844. return ret;
  19845. };
  19846. Object.defineProperty(Camera.prototype, "globalPosition", {
  19847. get: function () {
  19848. return this._globalPosition;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Camera.prototype.getActiveMeshes = function () {
  19854. return this._activeMeshes;
  19855. };
  19856. Camera.prototype.isActiveMesh = function (mesh) {
  19857. return (this._activeMeshes.indexOf(mesh) !== -1);
  19858. };
  19859. //Cache
  19860. Camera.prototype._initCache = function () {
  19861. _super.prototype._initCache.call(this);
  19862. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19863. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19864. this._cache.mode = undefined;
  19865. this._cache.minZ = undefined;
  19866. this._cache.maxZ = undefined;
  19867. this._cache.fov = undefined;
  19868. this._cache.fovMode = undefined;
  19869. this._cache.aspectRatio = undefined;
  19870. this._cache.orthoLeft = undefined;
  19871. this._cache.orthoRight = undefined;
  19872. this._cache.orthoBottom = undefined;
  19873. this._cache.orthoTop = undefined;
  19874. this._cache.renderWidth = undefined;
  19875. this._cache.renderHeight = undefined;
  19876. };
  19877. Camera.prototype._updateCache = function (ignoreParentClass) {
  19878. if (!ignoreParentClass) {
  19879. _super.prototype._updateCache.call(this);
  19880. }
  19881. this._cache.position.copyFrom(this.position);
  19882. this._cache.upVector.copyFrom(this.upVector);
  19883. };
  19884. // Synchronized
  19885. Camera.prototype._isSynchronized = function () {
  19886. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19887. };
  19888. Camera.prototype._isSynchronizedViewMatrix = function () {
  19889. if (!_super.prototype._isSynchronized.call(this))
  19890. return false;
  19891. return this._cache.position.equals(this.position)
  19892. && this._cache.upVector.equals(this.upVector)
  19893. && this.isSynchronizedWithParent();
  19894. };
  19895. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19896. var check = this._cache.mode === this.mode
  19897. && this._cache.minZ === this.minZ
  19898. && this._cache.maxZ === this.maxZ;
  19899. if (!check) {
  19900. return false;
  19901. }
  19902. var engine = this.getEngine();
  19903. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19904. check = this._cache.fov === this.fov
  19905. && this._cache.fovMode === this.fovMode
  19906. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19907. }
  19908. else {
  19909. check = this._cache.orthoLeft === this.orthoLeft
  19910. && this._cache.orthoRight === this.orthoRight
  19911. && this._cache.orthoBottom === this.orthoBottom
  19912. && this._cache.orthoTop === this.orthoTop
  19913. && this._cache.renderWidth === engine.getRenderWidth()
  19914. && this._cache.renderHeight === engine.getRenderHeight();
  19915. }
  19916. return check;
  19917. };
  19918. // Controls
  19919. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19920. };
  19921. Camera.prototype.detachControl = function (element) {
  19922. };
  19923. Camera.prototype.update = function () {
  19924. this._checkInputs();
  19925. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19926. this._updateRigCameras();
  19927. }
  19928. };
  19929. Camera.prototype._checkInputs = function () {
  19930. this.onAfterCheckInputsObservable.notifyObservers(this);
  19931. };
  19932. Object.defineProperty(Camera.prototype, "rigCameras", {
  19933. get: function () {
  19934. return this._rigCameras;
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19940. get: function () {
  19941. return this._rigPostProcess;
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19947. // invalidate framebuffer
  19948. if (this._postProcesses.length > 0) {
  19949. this._postProcesses[0].markTextureDirty();
  19950. }
  19951. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19952. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19953. var cam = this._rigCameras[i];
  19954. var rigPostProcess = cam._rigPostProcess;
  19955. // for VR rig, there does not have to be a post process
  19956. if (rigPostProcess) {
  19957. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19958. if (isPass) {
  19959. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19960. cam.isIntermediate = this._postProcesses.length === 0;
  19961. }
  19962. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19963. rigPostProcess.markTextureDirty();
  19964. }
  19965. else {
  19966. cam._postProcesses = this._postProcesses.slice(0);
  19967. }
  19968. }
  19969. };
  19970. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19971. if (insertAt === void 0) { insertAt = null; }
  19972. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19973. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19974. return 0;
  19975. }
  19976. if (insertAt == null || insertAt < 0) {
  19977. this._postProcesses.push(postProcess);
  19978. }
  19979. else {
  19980. this._postProcesses.splice(insertAt, 0, postProcess);
  19981. }
  19982. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19983. return this._postProcesses.indexOf(postProcess);
  19984. };
  19985. Camera.prototype.detachPostProcess = function (postProcess) {
  19986. var idx = this._postProcesses.indexOf(postProcess);
  19987. if (idx !== -1) {
  19988. this._postProcesses.splice(idx, 1);
  19989. }
  19990. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19991. };
  19992. Camera.prototype.getWorldMatrix = function () {
  19993. if (!this._worldMatrix) {
  19994. this._worldMatrix = BABYLON.Matrix.Identity();
  19995. }
  19996. var viewMatrix = this.getViewMatrix();
  19997. viewMatrix.invertToRef(this._worldMatrix);
  19998. return this._worldMatrix;
  19999. };
  20000. Camera.prototype._getViewMatrix = function () {
  20001. return BABYLON.Matrix.Identity();
  20002. };
  20003. Camera.prototype.getViewMatrix = function (force) {
  20004. if (!force && this._isSynchronizedViewMatrix()) {
  20005. return this._computedViewMatrix;
  20006. }
  20007. this.updateCache();
  20008. this._computedViewMatrix = this._getViewMatrix();
  20009. this._currentRenderId = this.getScene().getRenderId();
  20010. this._refreshFrustumPlanes = true;
  20011. if (!this.parent || !this.parent.getWorldMatrix) {
  20012. this._globalPosition.copyFrom(this.position);
  20013. }
  20014. else {
  20015. if (!this._worldMatrix) {
  20016. this._worldMatrix = BABYLON.Matrix.Identity();
  20017. }
  20018. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20019. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20020. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20021. this._computedViewMatrix.invert();
  20022. this._markSyncedWithParent();
  20023. }
  20024. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20025. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20026. }
  20027. this.onViewMatrixChangedObservable.notifyObservers(this);
  20028. return this._computedViewMatrix;
  20029. };
  20030. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20031. this._doNotComputeProjectionMatrix = true;
  20032. if (projection !== undefined) {
  20033. this._projectionMatrix = projection;
  20034. }
  20035. };
  20036. ;
  20037. Camera.prototype.unfreezeProjectionMatrix = function () {
  20038. this._doNotComputeProjectionMatrix = false;
  20039. };
  20040. ;
  20041. Camera.prototype.getProjectionMatrix = function (force) {
  20042. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20043. return this._projectionMatrix;
  20044. }
  20045. // Cache
  20046. this._cache.mode = this.mode;
  20047. this._cache.minZ = this.minZ;
  20048. this._cache.maxZ = this.maxZ;
  20049. // Matrix
  20050. this._refreshFrustumPlanes = true;
  20051. var engine = this.getEngine();
  20052. var scene = this.getScene();
  20053. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20054. this._cache.fov = this.fov;
  20055. this._cache.fovMode = this.fovMode;
  20056. this._cache.aspectRatio = engine.getAspectRatio(this);
  20057. if (this.minZ <= 0) {
  20058. this.minZ = 0.1;
  20059. }
  20060. if (scene.useRightHandedSystem) {
  20061. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20062. }
  20063. else {
  20064. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20065. }
  20066. }
  20067. else {
  20068. var halfWidth = engine.getRenderWidth() / 2.0;
  20069. var halfHeight = engine.getRenderHeight() / 2.0;
  20070. if (scene.useRightHandedSystem) {
  20071. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20072. }
  20073. else {
  20074. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20075. }
  20076. this._cache.orthoLeft = this.orthoLeft;
  20077. this._cache.orthoRight = this.orthoRight;
  20078. this._cache.orthoBottom = this.orthoBottom;
  20079. this._cache.orthoTop = this.orthoTop;
  20080. this._cache.renderWidth = engine.getRenderWidth();
  20081. this._cache.renderHeight = engine.getRenderHeight();
  20082. }
  20083. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20084. return this._projectionMatrix;
  20085. };
  20086. Camera.prototype.getTranformationMatrix = function () {
  20087. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20088. return this._transformMatrix;
  20089. };
  20090. Camera.prototype.updateFrustumPlanes = function () {
  20091. if (!this._refreshFrustumPlanes) {
  20092. return;
  20093. }
  20094. this.getTranformationMatrix();
  20095. if (!this._frustumPlanes) {
  20096. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20097. }
  20098. else {
  20099. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20100. }
  20101. this._refreshFrustumPlanes = false;
  20102. };
  20103. Camera.prototype.isInFrustum = function (target) {
  20104. this.updateFrustumPlanes();
  20105. return target.isInFrustum(this._frustumPlanes);
  20106. };
  20107. Camera.prototype.isCompletelyInFrustum = function (target) {
  20108. this.updateFrustumPlanes();
  20109. return target.isCompletelyInFrustum(this._frustumPlanes);
  20110. };
  20111. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20112. if (length === void 0) { length = 100; }
  20113. if (!transform) {
  20114. transform = this.getWorldMatrix();
  20115. }
  20116. if (!origin) {
  20117. origin = this.position;
  20118. }
  20119. var forward = new BABYLON.Vector3(0, 0, 1);
  20120. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20121. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20122. return new BABYLON.Ray(origin, direction, length);
  20123. };
  20124. Camera.prototype.dispose = function () {
  20125. // Observables
  20126. this.onViewMatrixChangedObservable.clear();
  20127. this.onProjectionMatrixChangedObservable.clear();
  20128. this.onAfterCheckInputsObservable.clear();
  20129. this.onRestoreStateObservable.clear();
  20130. // Inputs
  20131. if (this.inputs) {
  20132. this.inputs.clear();
  20133. }
  20134. // Animations
  20135. this.getScene().stopAnimation(this);
  20136. // Remove from scene
  20137. this.getScene().removeCamera(this);
  20138. while (this._rigCameras.length > 0) {
  20139. var camera = this._rigCameras.pop();
  20140. if (camera) {
  20141. camera.dispose();
  20142. }
  20143. }
  20144. // Postprocesses
  20145. if (this._rigPostProcess) {
  20146. this._rigPostProcess.dispose(this);
  20147. this._rigPostProcess = null;
  20148. this._postProcesses = [];
  20149. }
  20150. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20151. this._rigPostProcess = null;
  20152. this._postProcesses = [];
  20153. }
  20154. else {
  20155. var i = this._postProcesses.length;
  20156. while (--i >= 0) {
  20157. this._postProcesses[i].dispose(this);
  20158. }
  20159. }
  20160. // Render targets
  20161. var i = this.customRenderTargets.length;
  20162. while (--i >= 0) {
  20163. this.customRenderTargets[i].dispose();
  20164. }
  20165. this.customRenderTargets = [];
  20166. // Active Meshes
  20167. this._activeMeshes.dispose();
  20168. _super.prototype.dispose.call(this);
  20169. };
  20170. Object.defineProperty(Camera.prototype, "leftCamera", {
  20171. // ---- Camera rigs section ----
  20172. get: function () {
  20173. if (this._rigCameras.length < 1) {
  20174. return null;
  20175. }
  20176. return this._rigCameras[0];
  20177. },
  20178. enumerable: true,
  20179. configurable: true
  20180. });
  20181. Object.defineProperty(Camera.prototype, "rightCamera", {
  20182. get: function () {
  20183. if (this._rigCameras.length < 2) {
  20184. return null;
  20185. }
  20186. return this._rigCameras[1];
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Camera.prototype.getLeftTarget = function () {
  20192. if (this._rigCameras.length < 1) {
  20193. return null;
  20194. }
  20195. return this._rigCameras[0].getTarget();
  20196. };
  20197. Camera.prototype.getRightTarget = function () {
  20198. if (this._rigCameras.length < 2) {
  20199. return null;
  20200. }
  20201. return this._rigCameras[1].getTarget();
  20202. };
  20203. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20204. if (this.cameraRigMode === mode) {
  20205. return;
  20206. }
  20207. while (this._rigCameras.length > 0) {
  20208. var camera = this._rigCameras.pop();
  20209. if (camera) {
  20210. camera.dispose();
  20211. }
  20212. }
  20213. this.cameraRigMode = mode;
  20214. this._cameraRigParams = {};
  20215. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20216. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20217. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20218. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20219. // create the rig cameras, unless none
  20220. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20221. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20222. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20223. if (leftCamera && rightCamera) {
  20224. this._rigCameras.push(leftCamera);
  20225. this._rigCameras.push(rightCamera);
  20226. }
  20227. }
  20228. switch (this.cameraRigMode) {
  20229. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20230. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20231. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20232. break;
  20233. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20234. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20235. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20236. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20237. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20238. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20239. break;
  20240. case Camera.RIG_MODE_VR:
  20241. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20242. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20243. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20244. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20245. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20246. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20247. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20248. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20249. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20250. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20251. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20252. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20253. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20254. if (metrics.compensateDistortion) {
  20255. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20256. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20257. }
  20258. break;
  20259. case Camera.RIG_MODE_WEBVR:
  20260. if (rigParams.vrDisplay) {
  20261. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20262. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20263. //Left eye
  20264. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20265. this._rigCameras[0].setCameraRigParameter("left", true);
  20266. //leaving this for future reference
  20267. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20268. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20269. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20270. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20271. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20272. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20273. this._rigCameras[0].parent = this;
  20274. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20275. //Right eye
  20276. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20277. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20278. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20279. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20280. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20281. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20282. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20283. this._rigCameras[1].parent = this;
  20284. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20285. if (Camera.UseAlternateWebVRRendering) {
  20286. this._rigCameras[1]._skipRendering = true;
  20287. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20288. }
  20289. }
  20290. break;
  20291. }
  20292. this._cascadePostProcessesToRigCams();
  20293. this.update();
  20294. };
  20295. Camera.prototype._getVRProjectionMatrix = function () {
  20296. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20297. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20298. return this._projectionMatrix;
  20299. };
  20300. Camera.prototype._updateCameraRotationMatrix = function () {
  20301. //Here for WebVR
  20302. };
  20303. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20304. //Here for WebVR
  20305. };
  20306. /**
  20307. * This function MUST be overwritten by the different WebVR cameras available.
  20308. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20309. */
  20310. Camera.prototype._getWebVRProjectionMatrix = function () {
  20311. return BABYLON.Matrix.Identity();
  20312. };
  20313. /**
  20314. * This function MUST be overwritten by the different WebVR cameras available.
  20315. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20316. */
  20317. Camera.prototype._getWebVRViewMatrix = function () {
  20318. return BABYLON.Matrix.Identity();
  20319. };
  20320. Camera.prototype.setCameraRigParameter = function (name, value) {
  20321. if (!this._cameraRigParams) {
  20322. this._cameraRigParams = {};
  20323. }
  20324. this._cameraRigParams[name] = value;
  20325. //provisionnally:
  20326. if (name === "interaxialDistance") {
  20327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20328. }
  20329. };
  20330. /**
  20331. * needs to be overridden by children so sub has required properties to be copied
  20332. */
  20333. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20334. return null;
  20335. };
  20336. /**
  20337. * May need to be overridden by children
  20338. */
  20339. Camera.prototype._updateRigCameras = function () {
  20340. for (var i = 0; i < this._rigCameras.length; i++) {
  20341. this._rigCameras[i].minZ = this.minZ;
  20342. this._rigCameras[i].maxZ = this.maxZ;
  20343. this._rigCameras[i].fov = this.fov;
  20344. }
  20345. // only update viewport when ANAGLYPH
  20346. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20347. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20348. }
  20349. };
  20350. Camera.prototype._setupInputs = function () {
  20351. };
  20352. Camera.prototype.serialize = function () {
  20353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20354. // Type
  20355. serializationObject.type = this.getClassName();
  20356. // Parent
  20357. if (this.parent) {
  20358. serializationObject.parentId = this.parent.id;
  20359. }
  20360. if (this.inputs) {
  20361. this.inputs.serialize(serializationObject);
  20362. }
  20363. // Animations
  20364. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20365. serializationObject.ranges = this.serializeAnimationRanges();
  20366. return serializationObject;
  20367. };
  20368. Camera.prototype.clone = function (name) {
  20369. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20370. };
  20371. Camera.prototype.getDirection = function (localAxis) {
  20372. var result = BABYLON.Vector3.Zero();
  20373. this.getDirectionToRef(localAxis, result);
  20374. return result;
  20375. };
  20376. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20377. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20378. };
  20379. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20380. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20381. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20382. switch (type) {
  20383. case "ArcRotateCamera":
  20384. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20385. case "DeviceOrientationCamera":
  20386. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20387. case "FollowCamera":
  20388. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20389. case "ArcFollowCamera":
  20390. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20391. case "GamepadCamera":
  20392. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20393. case "TouchCamera":
  20394. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20395. case "VirtualJoysticksCamera":
  20396. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20397. case "WebVRFreeCamera":
  20398. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20399. case "WebVRGamepadCamera":
  20400. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20401. case "VRDeviceOrientationFreeCamera":
  20402. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20403. case "VRDeviceOrientationGamepadCamera":
  20404. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20405. case "AnaglyphArcRotateCamera":
  20406. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20407. case "AnaglyphFreeCamera":
  20408. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20409. case "AnaglyphGamepadCamera":
  20410. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20411. case "AnaglyphUniversalCamera":
  20412. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20413. case "StereoscopicArcRotateCamera":
  20414. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20415. case "StereoscopicFreeCamera":
  20416. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20417. case "StereoscopicGamepadCamera":
  20418. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20419. case "StereoscopicUniversalCamera":
  20420. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20421. case "FreeCamera":// Forcing Universal here
  20422. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20423. default:// Universal Camera is the default value
  20424. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20425. }
  20426. };
  20427. Camera.prototype.computeWorldMatrix = function () {
  20428. return this.getWorldMatrix();
  20429. };
  20430. Camera.Parse = function (parsedCamera, scene) {
  20431. var type = parsedCamera.type;
  20432. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20433. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20434. // Parent
  20435. if (parsedCamera.parentId) {
  20436. camera._waitingParentId = parsedCamera.parentId;
  20437. }
  20438. //If camera has an input manager, let it parse inputs settings
  20439. if (camera.inputs) {
  20440. camera.inputs.parse(parsedCamera);
  20441. camera._setupInputs();
  20442. }
  20443. if (camera.setPosition) {
  20444. camera.position.copyFromFloats(0, 0, 0);
  20445. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20446. }
  20447. // Target
  20448. if (parsedCamera.target) {
  20449. if (camera.setTarget) {
  20450. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20451. }
  20452. }
  20453. // Apply 3d rig, when found
  20454. if (parsedCamera.cameraRigMode) {
  20455. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20456. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20457. }
  20458. // Animations
  20459. if (parsedCamera.animations) {
  20460. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20461. var parsedAnimation = parsedCamera.animations[animationIndex];
  20462. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20463. }
  20464. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20465. }
  20466. if (parsedCamera.autoAnimate) {
  20467. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20468. }
  20469. return camera;
  20470. };
  20471. // Statics
  20472. Camera._PERSPECTIVE_CAMERA = 0;
  20473. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20474. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20475. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20476. Camera._RIG_MODE_NONE = 0;
  20477. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20478. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20480. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20481. Camera._RIG_MODE_VR = 20;
  20482. Camera._RIG_MODE_WEBVR = 21;
  20483. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20484. Camera.UseAlternateWebVRRendering = false;
  20485. __decorate([
  20486. BABYLON.serializeAsVector3()
  20487. ], Camera.prototype, "position", void 0);
  20488. __decorate([
  20489. BABYLON.serializeAsVector3()
  20490. ], Camera.prototype, "upVector", void 0);
  20491. __decorate([
  20492. BABYLON.serialize()
  20493. ], Camera.prototype, "orthoLeft", void 0);
  20494. __decorate([
  20495. BABYLON.serialize()
  20496. ], Camera.prototype, "orthoRight", void 0);
  20497. __decorate([
  20498. BABYLON.serialize()
  20499. ], Camera.prototype, "orthoBottom", void 0);
  20500. __decorate([
  20501. BABYLON.serialize()
  20502. ], Camera.prototype, "orthoTop", void 0);
  20503. __decorate([
  20504. BABYLON.serialize()
  20505. ], Camera.prototype, "fov", void 0);
  20506. __decorate([
  20507. BABYLON.serialize()
  20508. ], Camera.prototype, "minZ", void 0);
  20509. __decorate([
  20510. BABYLON.serialize()
  20511. ], Camera.prototype, "maxZ", void 0);
  20512. __decorate([
  20513. BABYLON.serialize()
  20514. ], Camera.prototype, "inertia", void 0);
  20515. __decorate([
  20516. BABYLON.serialize()
  20517. ], Camera.prototype, "mode", void 0);
  20518. __decorate([
  20519. BABYLON.serialize()
  20520. ], Camera.prototype, "layerMask", void 0);
  20521. __decorate([
  20522. BABYLON.serialize()
  20523. ], Camera.prototype, "fovMode", void 0);
  20524. __decorate([
  20525. BABYLON.serialize()
  20526. ], Camera.prototype, "cameraRigMode", void 0);
  20527. __decorate([
  20528. BABYLON.serialize()
  20529. ], Camera.prototype, "interaxialDistance", void 0);
  20530. __decorate([
  20531. BABYLON.serialize()
  20532. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20533. return Camera;
  20534. }(BABYLON.Node));
  20535. BABYLON.Camera = Camera;
  20536. })(BABYLON || (BABYLON = {}));
  20537. //# sourceMappingURL=babylon.camera.js.map
  20538. var BABYLON;
  20539. (function (BABYLON) {
  20540. var RenderingManager = /** @class */ (function () {
  20541. function RenderingManager(scene) {
  20542. this._renderingGroups = new Array();
  20543. this._autoClearDepthStencil = {};
  20544. this._customOpaqueSortCompareFn = {};
  20545. this._customAlphaTestSortCompareFn = {};
  20546. this._customTransparentSortCompareFn = {};
  20547. this._renderinGroupInfo = null;
  20548. this._scene = scene;
  20549. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20550. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20551. }
  20552. }
  20553. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20554. if (depth === void 0) { depth = true; }
  20555. if (stencil === void 0) { stencil = true; }
  20556. if (this._depthStencilBufferAlreadyCleaned) {
  20557. return;
  20558. }
  20559. this._scene.getEngine().clear(null, false, depth, stencil);
  20560. this._depthStencilBufferAlreadyCleaned = true;
  20561. };
  20562. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20563. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20564. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20565. var info = null;
  20566. if (observable) {
  20567. if (!this._renderinGroupInfo) {
  20568. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20569. }
  20570. info = this._renderinGroupInfo;
  20571. info.scene = this._scene;
  20572. info.camera = this._scene.activeCamera;
  20573. }
  20574. // Dispatch sprites
  20575. if (renderSprites) {
  20576. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20577. var manager = this._scene.spriteManagers[index];
  20578. this.dispatchSprites(manager);
  20579. }
  20580. }
  20581. // Render
  20582. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20583. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20584. var renderingGroup = this._renderingGroups[index];
  20585. if (!renderingGroup && !observable)
  20586. continue;
  20587. var renderingGroupMask = 0;
  20588. // Fire PRECLEAR stage
  20589. if (observable && info) {
  20590. renderingGroupMask = Math.pow(2, index);
  20591. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20592. info.renderingGroupId = index;
  20593. observable.notifyObservers(info, renderingGroupMask);
  20594. }
  20595. // Clear depth/stencil if needed
  20596. if (RenderingManager.AUTOCLEAR) {
  20597. var autoClear = this._autoClearDepthStencil[index];
  20598. if (autoClear && autoClear.autoClear) {
  20599. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20600. }
  20601. }
  20602. if (observable && info) {
  20603. // Fire PREOPAQUE stage
  20604. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20605. observable.notifyObservers(info, renderingGroupMask);
  20606. // Fire PRETRANSPARENT stage
  20607. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20608. observable.notifyObservers(info, renderingGroupMask);
  20609. }
  20610. if (renderingGroup)
  20611. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20612. // Fire POSTTRANSPARENT stage
  20613. if (observable && info) {
  20614. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20615. observable.notifyObservers(info, renderingGroupMask);
  20616. }
  20617. }
  20618. };
  20619. RenderingManager.prototype.reset = function () {
  20620. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20621. var renderingGroup = this._renderingGroups[index];
  20622. if (renderingGroup) {
  20623. renderingGroup.prepare();
  20624. }
  20625. }
  20626. };
  20627. RenderingManager.prototype.dispose = function () {
  20628. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20629. var renderingGroup = this._renderingGroups[index];
  20630. if (renderingGroup) {
  20631. renderingGroup.dispose();
  20632. }
  20633. }
  20634. this._renderingGroups.length = 0;
  20635. };
  20636. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20637. if (this._renderingGroups[renderingGroupId] === undefined) {
  20638. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20639. }
  20640. };
  20641. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20642. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20643. this._prepareRenderingGroup(renderingGroupId);
  20644. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20645. };
  20646. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20647. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20648. this._prepareRenderingGroup(renderingGroupId);
  20649. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20650. };
  20651. /**
  20652. * @param subMesh The submesh to dispatch
  20653. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20654. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20655. */
  20656. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20657. if (mesh === undefined) {
  20658. mesh = subMesh.getMesh();
  20659. }
  20660. var renderingGroupId = mesh.renderingGroupId || 0;
  20661. this._prepareRenderingGroup(renderingGroupId);
  20662. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20663. };
  20664. /**
  20665. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20666. * This allowed control for front to back rendering or reversly depending of the special needs.
  20667. *
  20668. * @param renderingGroupId The rendering group id corresponding to its index
  20669. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20670. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20671. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20672. */
  20673. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20674. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20675. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20676. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20677. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20678. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20679. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20680. if (this._renderingGroups[renderingGroupId]) {
  20681. var group = this._renderingGroups[renderingGroupId];
  20682. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20683. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20684. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20685. }
  20686. };
  20687. /**
  20688. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20689. *
  20690. * @param renderingGroupId The rendering group id corresponding to its index
  20691. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20692. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20693. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20694. */
  20695. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20696. if (depth === void 0) { depth = true; }
  20697. if (stencil === void 0) { stencil = true; }
  20698. this._autoClearDepthStencil[renderingGroupId] = {
  20699. autoClear: autoClearDepthStencil,
  20700. depth: depth,
  20701. stencil: stencil
  20702. };
  20703. };
  20704. /**
  20705. * The max id used for rendering groups (not included)
  20706. */
  20707. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20708. /**
  20709. * The min id used for rendering groups (included)
  20710. */
  20711. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20712. /**
  20713. * Used to globally prevent autoclearing scenes.
  20714. */
  20715. RenderingManager.AUTOCLEAR = true;
  20716. return RenderingManager;
  20717. }());
  20718. BABYLON.RenderingManager = RenderingManager;
  20719. })(BABYLON || (BABYLON = {}));
  20720. //# sourceMappingURL=babylon.renderingManager.js.map
  20721. var BABYLON;
  20722. (function (BABYLON) {
  20723. var RenderingGroup = /** @class */ (function () {
  20724. /**
  20725. * Creates a new rendering group.
  20726. * @param index The rendering group index
  20727. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20728. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20729. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20730. */
  20731. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20732. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20733. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20734. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20735. this.index = index;
  20736. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20737. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20738. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20739. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20740. this._particleSystems = new BABYLON.SmartArray(256);
  20741. this._spriteManagers = new BABYLON.SmartArray(256);
  20742. this._edgesRenderers = new BABYLON.SmartArray(16);
  20743. this._scene = scene;
  20744. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20745. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20746. this.transparentSortCompareFn = transparentSortCompareFn;
  20747. }
  20748. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20749. /**
  20750. * Set the opaque sort comparison function.
  20751. * If null the sub meshes will be render in the order they were created
  20752. */
  20753. set: function (value) {
  20754. this._opaqueSortCompareFn = value;
  20755. if (value) {
  20756. this._renderOpaque = this.renderOpaqueSorted;
  20757. }
  20758. else {
  20759. this._renderOpaque = RenderingGroup.renderUnsorted;
  20760. }
  20761. },
  20762. enumerable: true,
  20763. configurable: true
  20764. });
  20765. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20766. /**
  20767. * Set the alpha test sort comparison function.
  20768. * If null the sub meshes will be render in the order they were created
  20769. */
  20770. set: function (value) {
  20771. this._alphaTestSortCompareFn = value;
  20772. if (value) {
  20773. this._renderAlphaTest = this.renderAlphaTestSorted;
  20774. }
  20775. else {
  20776. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20777. }
  20778. },
  20779. enumerable: true,
  20780. configurable: true
  20781. });
  20782. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20783. /**
  20784. * Set the transparent sort comparison function.
  20785. * If null the sub meshes will be render in the order they were created
  20786. */
  20787. set: function (value) {
  20788. if (value) {
  20789. this._transparentSortCompareFn = value;
  20790. }
  20791. else {
  20792. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20793. }
  20794. this._renderTransparent = this.renderTransparentSorted;
  20795. },
  20796. enumerable: true,
  20797. configurable: true
  20798. });
  20799. /**
  20800. * Render all the sub meshes contained in the group.
  20801. * @param customRenderFunction Used to override the default render behaviour of the group.
  20802. * @returns true if rendered some submeshes.
  20803. */
  20804. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20805. if (customRenderFunction) {
  20806. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20807. return;
  20808. }
  20809. var engine = this._scene.getEngine();
  20810. // Depth only
  20811. if (this._depthOnlySubMeshes.length !== 0) {
  20812. engine.setColorWrite(false);
  20813. this._renderAlphaTest(this._depthOnlySubMeshes);
  20814. engine.setColorWrite(true);
  20815. }
  20816. // Opaque
  20817. if (this._opaqueSubMeshes.length !== 0) {
  20818. this._renderOpaque(this._opaqueSubMeshes);
  20819. }
  20820. // Alpha test
  20821. if (this._alphaTestSubMeshes.length !== 0) {
  20822. this._renderAlphaTest(this._alphaTestSubMeshes);
  20823. }
  20824. var stencilState = engine.getStencilBuffer();
  20825. engine.setStencilBuffer(false);
  20826. // Sprites
  20827. if (renderSprites) {
  20828. this._renderSprites();
  20829. }
  20830. // Particles
  20831. if (renderParticles) {
  20832. this._renderParticles(activeMeshes);
  20833. }
  20834. if (this.onBeforeTransparentRendering) {
  20835. this.onBeforeTransparentRendering();
  20836. }
  20837. // Transparent
  20838. if (this._transparentSubMeshes.length !== 0) {
  20839. this._renderTransparent(this._transparentSubMeshes);
  20840. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20841. }
  20842. // Set back stencil to false in case it changes before the edge renderer.
  20843. engine.setStencilBuffer(false);
  20844. // Edges
  20845. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20846. this._edgesRenderers.data[edgesRendererIndex].render();
  20847. }
  20848. // Restore Stencil state.
  20849. engine.setStencilBuffer(stencilState);
  20850. };
  20851. /**
  20852. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20853. * @param subMeshes The submeshes to render
  20854. */
  20855. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20856. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20857. };
  20858. /**
  20859. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20860. * @param subMeshes The submeshes to render
  20861. */
  20862. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20863. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20864. };
  20865. /**
  20866. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20867. * @param subMeshes The submeshes to render
  20868. */
  20869. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20870. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20871. };
  20872. /**
  20873. * Renders the submeshes in a specified order.
  20874. * @param subMeshes The submeshes to sort before render
  20875. * @param sortCompareFn The comparison function use to sort
  20876. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20877. * @param transparent Specifies to activate blending if true
  20878. */
  20879. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20880. var subIndex = 0;
  20881. var subMesh;
  20882. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20883. for (; subIndex < subMeshes.length; subIndex++) {
  20884. subMesh = subMeshes.data[subIndex];
  20885. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20886. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20887. }
  20888. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20889. if (sortCompareFn) {
  20890. sortedArray.sort(sortCompareFn);
  20891. }
  20892. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20893. subMesh = sortedArray[subIndex];
  20894. if (transparent) {
  20895. var material = subMesh.getMaterial();
  20896. if (material && material.needDepthPrePass) {
  20897. var engine = material.getScene().getEngine();
  20898. engine.setColorWrite(false);
  20899. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20900. subMesh.render(false);
  20901. engine.setColorWrite(true);
  20902. }
  20903. }
  20904. subMesh.render(transparent);
  20905. }
  20906. };
  20907. /**
  20908. * Renders the submeshes in the order they were dispatched (no sort applied).
  20909. * @param subMeshes The submeshes to render
  20910. */
  20911. RenderingGroup.renderUnsorted = function (subMeshes) {
  20912. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20913. var submesh = subMeshes.data[subIndex];
  20914. submesh.render(false);
  20915. }
  20916. };
  20917. /**
  20918. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20919. * are rendered back to front if in the same alpha index.
  20920. *
  20921. * @param a The first submesh
  20922. * @param b The second submesh
  20923. * @returns The result of the comparison
  20924. */
  20925. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20926. // Alpha index first
  20927. if (a._alphaIndex > b._alphaIndex) {
  20928. return 1;
  20929. }
  20930. if (a._alphaIndex < b._alphaIndex) {
  20931. return -1;
  20932. }
  20933. // Then distance to camera
  20934. return RenderingGroup.backToFrontSortCompare(a, b);
  20935. };
  20936. /**
  20937. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20938. * are rendered back to front.
  20939. *
  20940. * @param a The first submesh
  20941. * @param b The second submesh
  20942. * @returns The result of the comparison
  20943. */
  20944. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20945. // Then distance to camera
  20946. if (a._distanceToCamera < b._distanceToCamera) {
  20947. return 1;
  20948. }
  20949. if (a._distanceToCamera > b._distanceToCamera) {
  20950. return -1;
  20951. }
  20952. return 0;
  20953. };
  20954. /**
  20955. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20956. * are rendered front to back (prevent overdraw).
  20957. *
  20958. * @param a The first submesh
  20959. * @param b The second submesh
  20960. * @returns The result of the comparison
  20961. */
  20962. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20963. // Then distance to camera
  20964. if (a._distanceToCamera < b._distanceToCamera) {
  20965. return -1;
  20966. }
  20967. if (a._distanceToCamera > b._distanceToCamera) {
  20968. return 1;
  20969. }
  20970. return 0;
  20971. };
  20972. /**
  20973. * Resets the different lists of submeshes to prepare a new frame.
  20974. */
  20975. RenderingGroup.prototype.prepare = function () {
  20976. this._opaqueSubMeshes.reset();
  20977. this._transparentSubMeshes.reset();
  20978. this._alphaTestSubMeshes.reset();
  20979. this._depthOnlySubMeshes.reset();
  20980. this._particleSystems.reset();
  20981. this._spriteManagers.reset();
  20982. this._edgesRenderers.reset();
  20983. };
  20984. RenderingGroup.prototype.dispose = function () {
  20985. this._opaqueSubMeshes.dispose();
  20986. this._transparentSubMeshes.dispose();
  20987. this._alphaTestSubMeshes.dispose();
  20988. this._depthOnlySubMeshes.dispose();
  20989. this._particleSystems.dispose();
  20990. this._spriteManagers.dispose();
  20991. this._edgesRenderers.dispose();
  20992. };
  20993. /**
  20994. * Inserts the submesh in its correct queue depending on its material.
  20995. * @param subMesh The submesh to dispatch
  20996. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20997. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20998. */
  20999. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21000. // Get mesh and materials if not provided
  21001. if (mesh === undefined) {
  21002. mesh = subMesh.getMesh();
  21003. }
  21004. if (material === undefined) {
  21005. material = subMesh.getMaterial();
  21006. }
  21007. if (material === null || material === undefined) {
  21008. return;
  21009. }
  21010. if (material.needAlphaBlendingForMesh(mesh)) {
  21011. this._transparentSubMeshes.push(subMesh);
  21012. }
  21013. else if (material.needAlphaTesting()) {
  21014. if (material.needDepthPrePass) {
  21015. this._depthOnlySubMeshes.push(subMesh);
  21016. }
  21017. this._alphaTestSubMeshes.push(subMesh);
  21018. }
  21019. else {
  21020. if (material.needDepthPrePass) {
  21021. this._depthOnlySubMeshes.push(subMesh);
  21022. }
  21023. this._opaqueSubMeshes.push(subMesh); // Opaque
  21024. }
  21025. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21026. this._edgesRenderers.push(mesh._edgesRenderer);
  21027. }
  21028. };
  21029. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21030. this._spriteManagers.push(spriteManager);
  21031. };
  21032. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21033. this._particleSystems.push(particleSystem);
  21034. };
  21035. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21036. if (this._particleSystems.length === 0) {
  21037. return;
  21038. }
  21039. // Particles
  21040. var activeCamera = this._scene.activeCamera;
  21041. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21042. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21043. var particleSystem = this._particleSystems.data[particleIndex];
  21044. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21045. continue;
  21046. }
  21047. var emitter = particleSystem.emitter;
  21048. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21049. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21050. }
  21051. }
  21052. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21053. };
  21054. RenderingGroup.prototype._renderSprites = function () {
  21055. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21056. return;
  21057. }
  21058. // Sprites
  21059. var activeCamera = this._scene.activeCamera;
  21060. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21061. for (var id = 0; id < this._spriteManagers.length; id++) {
  21062. var spriteManager = this._spriteManagers.data[id];
  21063. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21064. spriteManager.render();
  21065. }
  21066. }
  21067. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21068. };
  21069. return RenderingGroup;
  21070. }());
  21071. BABYLON.RenderingGroup = RenderingGroup;
  21072. })(BABYLON || (BABYLON = {}));
  21073. //# sourceMappingURL=babylon.renderingGroup.js.map
  21074. var BABYLON;
  21075. (function (BABYLON) {
  21076. var ClickInfo = /** @class */ (function () {
  21077. function ClickInfo() {
  21078. this._singleClick = false;
  21079. this._doubleClick = false;
  21080. this._hasSwiped = false;
  21081. this._ignore = false;
  21082. }
  21083. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21084. get: function () {
  21085. return this._singleClick;
  21086. },
  21087. set: function (b) {
  21088. this._singleClick = b;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21094. get: function () {
  21095. return this._doubleClick;
  21096. },
  21097. set: function (b) {
  21098. this._doubleClick = b;
  21099. },
  21100. enumerable: true,
  21101. configurable: true
  21102. });
  21103. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21104. get: function () {
  21105. return this._hasSwiped;
  21106. },
  21107. set: function (b) {
  21108. this._hasSwiped = b;
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21114. get: function () {
  21115. return this._ignore;
  21116. },
  21117. set: function (b) {
  21118. this._ignore = b;
  21119. },
  21120. enumerable: true,
  21121. configurable: true
  21122. });
  21123. return ClickInfo;
  21124. }());
  21125. /**
  21126. * This class is used by the onRenderingGroupObservable
  21127. */
  21128. var RenderingGroupInfo = /** @class */ (function () {
  21129. function RenderingGroupInfo() {
  21130. }
  21131. /**
  21132. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21133. * This stage will be fired no matter what
  21134. */
  21135. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21136. /**
  21137. * Called before opaque object are rendered.
  21138. * This stage will be fired only if there's 3D Opaque content to render
  21139. */
  21140. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21141. /**
  21142. * Called after the opaque objects are rendered and before the transparent ones
  21143. * This stage will be fired only if there's 3D transparent content to render
  21144. */
  21145. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21146. /**
  21147. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21148. * This stage will be fired no matter what
  21149. */
  21150. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21151. return RenderingGroupInfo;
  21152. }());
  21153. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21154. /**
  21155. * Represents a scene to be rendered by the engine.
  21156. * @see http://doc.babylonjs.com/page.php?p=21911
  21157. */
  21158. var Scene = /** @class */ (function () {
  21159. /**
  21160. * @constructor
  21161. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21162. */
  21163. function Scene(engine) {
  21164. // Members
  21165. this.autoClear = true;
  21166. this.autoClearDepthAndStencil = true;
  21167. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21168. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21169. this.forceWireframe = false;
  21170. this._forcePointsCloud = false;
  21171. this.forceShowBoundingBoxes = false;
  21172. this.animationsEnabled = true;
  21173. this.useConstantAnimationDeltaTime = false;
  21174. this.constantlyUpdateMeshUnderPointer = false;
  21175. this.hoverCursor = "pointer";
  21176. this.defaultCursor = "";
  21177. /**
  21178. * This is used to call preventDefault() on pointer down
  21179. * in order to block unwanted artifacts like system double clicks
  21180. */
  21181. this.preventDefaultOnPointerDown = true;
  21182. // Metadata
  21183. this.metadata = null;
  21184. /**
  21185. * An event triggered when the scene is disposed.
  21186. * @type {BABYLON.Observable}
  21187. */
  21188. this.onDisposeObservable = new BABYLON.Observable();
  21189. /**
  21190. * An event triggered before rendering the scene (right after animations and physics)
  21191. * @type {BABYLON.Observable}
  21192. */
  21193. this.onBeforeRenderObservable = new BABYLON.Observable();
  21194. /**
  21195. * An event triggered after rendering the scene
  21196. * @type {BABYLON.Observable}
  21197. */
  21198. this.onAfterRenderObservable = new BABYLON.Observable();
  21199. /**
  21200. * An event triggered before animating the scene
  21201. * @type {BABYLON.Observable}
  21202. */
  21203. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21204. /**
  21205. * An event triggered after animations processing
  21206. * @type {BABYLON.Observable}
  21207. */
  21208. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21209. /**
  21210. * An event triggered before draw calls are ready to be sent
  21211. * @type {BABYLON.Observable}
  21212. */
  21213. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21214. /**
  21215. * An event triggered after draw calls have been sent
  21216. * @type {BABYLON.Observable}
  21217. */
  21218. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21219. /**
  21220. * An event triggered when physic simulation is about to be run
  21221. * @type {BABYLON.Observable}
  21222. */
  21223. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21224. /**
  21225. * An event triggered when physic simulation has been done
  21226. * @type {BABYLON.Observable}
  21227. */
  21228. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21229. /**
  21230. * An event triggered when the scene is ready
  21231. * @type {BABYLON.Observable}
  21232. */
  21233. this.onReadyObservable = new BABYLON.Observable();
  21234. /**
  21235. * An event triggered before rendering a camera
  21236. * @type {BABYLON.Observable}
  21237. */
  21238. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21239. /**
  21240. * An event triggered after rendering a camera
  21241. * @type {BABYLON.Observable}
  21242. */
  21243. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21244. /**
  21245. * An event triggered when active meshes evaluation is about to start
  21246. * @type {BABYLON.Observable}
  21247. */
  21248. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21249. /**
  21250. * An event triggered when active meshes evaluation is done
  21251. * @type {BABYLON.Observable}
  21252. */
  21253. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21254. /**
  21255. * An event triggered when particles rendering is about to start
  21256. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21257. * @type {BABYLON.Observable}
  21258. */
  21259. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21260. /**
  21261. * An event triggered when particles rendering is done
  21262. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21263. * @type {BABYLON.Observable}
  21264. */
  21265. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21266. /**
  21267. * An event triggered when sprites rendering is about to start
  21268. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21269. * @type {BABYLON.Observable}
  21270. */
  21271. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21272. /**
  21273. * An event triggered when sprites rendering is done
  21274. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onDataLoadedObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered when a camera is created
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when a camera is removed
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onCameraRemovedObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when a light is created
  21295. * @type {BABYLON.Observable}
  21296. */
  21297. this.onNewLightAddedObservable = new BABYLON.Observable();
  21298. /**
  21299. * An event triggered when a light is removed
  21300. * @type {BABYLON.Observable}
  21301. */
  21302. this.onLightRemovedObservable = new BABYLON.Observable();
  21303. /**
  21304. * An event triggered when a geometry is created
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered when a geometry is removed
  21310. * @type {BABYLON.Observable}
  21311. */
  21312. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21313. /**
  21314. * An event triggered when a transform node is created
  21315. * @type {BABYLON.Observable}
  21316. */
  21317. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21318. /**
  21319. * An event triggered when a transform node is removed
  21320. * @type {BABYLON.Observable}
  21321. */
  21322. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21323. /**
  21324. * An event triggered when a mesh is created
  21325. * @type {BABYLON.Observable}
  21326. */
  21327. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21328. /**
  21329. * An event triggered when a mesh is removed
  21330. * @type {BABYLON.Observable}
  21331. */
  21332. this.onMeshRemovedObservable = new BABYLON.Observable();
  21333. /**
  21334. * An event triggered when render targets are about to be rendered
  21335. * Can happen multiple times per frame.
  21336. * @type {BABYLON.Observable}
  21337. */
  21338. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21339. /**
  21340. * An event triggered when render targets were rendered.
  21341. * Can happen multiple times per frame.
  21342. * @type {BABYLON.Observable}
  21343. */
  21344. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21345. /**
  21346. * An event triggered before calculating deterministic simulation step
  21347. * @type {BABYLON.Observable}
  21348. */
  21349. this.onBeforeStepObservable = new BABYLON.Observable();
  21350. /**
  21351. * An event triggered after calculating deterministic simulation step
  21352. * @type {BABYLON.Observable}
  21353. */
  21354. this.onAfterStepObservable = new BABYLON.Observable();
  21355. /**
  21356. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21357. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21358. * 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)
  21359. */
  21360. this.onRenderingGroupObservable = new BABYLON.Observable();
  21361. // Animations
  21362. this.animations = [];
  21363. /**
  21364. * 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).
  21365. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21366. */
  21367. this.onPrePointerObservable = new BABYLON.Observable();
  21368. /**
  21369. * Observable event triggered each time an input event is received from the rendering canvas
  21370. */
  21371. this.onPointerObservable = new BABYLON.Observable();
  21372. this._meshPickProceed = false;
  21373. this._currentPickResult = null;
  21374. this._previousPickResult = null;
  21375. this._totalPointersPressed = 0;
  21376. this._doubleClickOccured = false;
  21377. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21378. this.cameraToUseForPointers = null;
  21379. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21380. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21381. this._startingPointerTime = 0;
  21382. this._previousStartingPointerTime = 0;
  21383. // Deterministic lockstep
  21384. this._timeAccumulator = 0;
  21385. this._currentStepId = 0;
  21386. this._currentInternalStep = 0;
  21387. // Keyboard
  21388. /**
  21389. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21390. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21391. */
  21392. this.onPreKeyboardObservable = new BABYLON.Observable();
  21393. /**
  21394. * Observable event triggered each time an keyboard event is received from the hosting window
  21395. */
  21396. this.onKeyboardObservable = new BABYLON.Observable();
  21397. // Coordinate system
  21398. /**
  21399. * use right-handed coordinate system on this scene.
  21400. * @type {boolean}
  21401. */
  21402. this._useRightHandedSystem = false;
  21403. // Fog
  21404. this._fogEnabled = true;
  21405. this._fogMode = Scene.FOGMODE_NONE;
  21406. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21407. this.fogDensity = 0.1;
  21408. this.fogStart = 0;
  21409. this.fogEnd = 1000.0;
  21410. // Lights
  21411. /**
  21412. * is shadow enabled on this scene.
  21413. * @type {boolean}
  21414. */
  21415. this._shadowsEnabled = true;
  21416. /**
  21417. * is light enabled on this scene.
  21418. * @type {boolean}
  21419. */
  21420. this._lightsEnabled = true;
  21421. /**
  21422. * All of the lights added to this scene.
  21423. * @see BABYLON.Light
  21424. * @type {BABYLON.Light[]}
  21425. */
  21426. this.lights = new Array();
  21427. // Cameras
  21428. /** All of the cameras added to this scene. */
  21429. this.cameras = new Array();
  21430. /** All of the active cameras added to this scene. */
  21431. this.activeCameras = new Array();
  21432. // Meshes
  21433. /**
  21434. * All of the tranform nodes added to this scene.
  21435. * @see BABYLON.TransformNode
  21436. * @type {BABYLON.TransformNode[]}
  21437. */
  21438. this.transformNodes = new Array();
  21439. /**
  21440. * All of the (abstract) meshes added to this scene.
  21441. * @see BABYLON.AbstractMesh
  21442. * @type {BABYLON.AbstractMesh[]}
  21443. */
  21444. this.meshes = new Array();
  21445. /**
  21446. * All of the animation groups added to this scene.
  21447. * @see BABYLON.AnimationGroup
  21448. * @type {BABYLON.AnimationGroup[]}
  21449. */
  21450. this.animationGroups = new Array();
  21451. // Geometries
  21452. this._geometries = new Array();
  21453. this.materials = new Array();
  21454. this.multiMaterials = new Array();
  21455. // Textures
  21456. this._texturesEnabled = true;
  21457. this.textures = new Array();
  21458. // Particles
  21459. this.particlesEnabled = true;
  21460. this.particleSystems = new Array();
  21461. // Sprites
  21462. this.spritesEnabled = true;
  21463. this.spriteManagers = new Array();
  21464. /**
  21465. * The list of layers (background and foreground) of the scene.
  21466. */
  21467. this.layers = new Array();
  21468. /**
  21469. * The list of effect layers (highlights/glow) contained in the scene.
  21470. */
  21471. this.effectLayers = new Array();
  21472. // Skeletons
  21473. this._skeletonsEnabled = true;
  21474. this.skeletons = new Array();
  21475. // Morph targets
  21476. this.morphTargetManagers = new Array();
  21477. // Lens flares
  21478. this.lensFlaresEnabled = true;
  21479. this.lensFlareSystems = new Array();
  21480. // Collisions
  21481. this.collisionsEnabled = true;
  21482. /** Defines the gravity applied to this scene */
  21483. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21484. // Postprocesses
  21485. this.postProcesses = new Array();
  21486. this.postProcessesEnabled = true;
  21487. // Customs render targets
  21488. this.renderTargetsEnabled = true;
  21489. this.dumpNextRenderTargets = false;
  21490. this.customRenderTargets = new Array();
  21491. // Imported meshes
  21492. this.importedMeshesFiles = new Array();
  21493. // Probes
  21494. this.probesEnabled = true;
  21495. this.reflectionProbes = new Array();
  21496. this._actionManagers = new Array();
  21497. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21498. // Procedural textures
  21499. this.proceduralTexturesEnabled = true;
  21500. this._proceduralTextures = new Array();
  21501. this.soundTracks = new Array();
  21502. this._audioEnabled = true;
  21503. this._headphone = false;
  21504. // Performance counters
  21505. this._totalVertices = new BABYLON.PerfCounter();
  21506. this._activeIndices = new BABYLON.PerfCounter();
  21507. this._activeParticles = new BABYLON.PerfCounter();
  21508. this._activeBones = new BABYLON.PerfCounter();
  21509. this._animationTime = 0;
  21510. this.animationTimeScale = 1;
  21511. this._renderId = 0;
  21512. this._executeWhenReadyTimeoutId = -1;
  21513. this._intermediateRendering = false;
  21514. this._viewUpdateFlag = -1;
  21515. this._projectionUpdateFlag = -1;
  21516. this._alternateViewUpdateFlag = -1;
  21517. this._alternateProjectionUpdateFlag = -1;
  21518. this._toBeDisposed = new BABYLON.SmartArray(256);
  21519. this._activeRequests = new Array();
  21520. this._pendingData = new Array();
  21521. this._isDisposed = false;
  21522. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21523. this._activeMeshes = new BABYLON.SmartArray(256);
  21524. this._processedMaterials = new BABYLON.SmartArray(256);
  21525. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21526. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21527. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21528. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21529. this._activeAnimatables = new Array();
  21530. this._transformMatrix = BABYLON.Matrix.Zero();
  21531. this._useAlternateCameraConfiguration = false;
  21532. this._alternateRendering = false;
  21533. this.requireLightSorting = false;
  21534. this._depthRenderer = {};
  21535. this._activeMeshesFrozen = false;
  21536. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21537. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21538. this._engine.scenes.push(this);
  21539. this._uid = null;
  21540. this._renderingManager = new BABYLON.RenderingManager(this);
  21541. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21542. if (BABYLON.OutlineRenderer) {
  21543. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21544. }
  21545. if (BABYLON.Tools.IsWindowObjectExist()) {
  21546. this.attachControl();
  21547. }
  21548. //simplification queue
  21549. if (BABYLON.SimplificationQueue) {
  21550. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21551. }
  21552. //collision coordinator initialization. For now legacy per default.
  21553. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21554. // Uniform Buffer
  21555. this._createUbo();
  21556. // Default Image processing definition.
  21557. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21558. }
  21559. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21560. /** The fog is deactivated */
  21561. get: function () {
  21562. return Scene._FOGMODE_NONE;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21568. /** The fog density is following an exponential function */
  21569. get: function () {
  21570. return Scene._FOGMODE_EXP;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21576. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21577. get: function () {
  21578. return Scene._FOGMODE_EXP2;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21584. /** The fog density is following a linear function. */
  21585. get: function () {
  21586. return Scene._FOGMODE_LINEAR;
  21587. },
  21588. enumerable: true,
  21589. configurable: true
  21590. });
  21591. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21592. /**
  21593. * Texture used in all pbr material as the reflection texture.
  21594. * As in the majority of the scene they are the same (exception for multi room and so on),
  21595. * this is easier to reference from here than from all the materials.
  21596. */
  21597. get: function () {
  21598. return this._environmentTexture;
  21599. },
  21600. /**
  21601. * Texture used in all pbr material as the reflection texture.
  21602. * As in the majority of the scene they are the same (exception for multi room and so on),
  21603. * this is easier to set here than in all the materials.
  21604. */
  21605. set: function (value) {
  21606. if (this._environmentTexture === value) {
  21607. return;
  21608. }
  21609. this._environmentTexture = value;
  21610. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21616. /**
  21617. * Default image processing configuration used either in the rendering
  21618. * Forward main pass or through the imageProcessingPostProcess if present.
  21619. * As in the majority of the scene they are the same (exception for multi camera),
  21620. * this is easier to reference from here than from all the materials and post process.
  21621. *
  21622. * No setter as we it is a shared configuration, you can set the values instead.
  21623. */
  21624. get: function () {
  21625. return this._imageProcessingConfiguration;
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21631. get: function () {
  21632. return this._forcePointsCloud;
  21633. },
  21634. set: function (value) {
  21635. if (this._forcePointsCloud === value) {
  21636. return;
  21637. }
  21638. this._forcePointsCloud = value;
  21639. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(Scene.prototype, "onDispose", {
  21645. /** A function to be executed when this scene is disposed. */
  21646. set: function (callback) {
  21647. if (this._onDisposeObserver) {
  21648. this.onDisposeObservable.remove(this._onDisposeObserver);
  21649. }
  21650. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Scene.prototype, "beforeRender", {
  21656. /** A function to be executed before rendering this scene */
  21657. set: function (callback) {
  21658. if (this._onBeforeRenderObserver) {
  21659. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21660. }
  21661. if (callback) {
  21662. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21663. }
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Scene.prototype, "afterRender", {
  21669. /** A function to be executed after rendering this scene */
  21670. set: function (callback) {
  21671. if (this._onAfterRenderObserver) {
  21672. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21673. }
  21674. if (callback) {
  21675. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21676. }
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21682. set: function (callback) {
  21683. if (this._onBeforeCameraRenderObserver) {
  21684. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21685. }
  21686. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21692. set: function (callback) {
  21693. if (this._onAfterCameraRenderObserver) {
  21694. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21695. }
  21696. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21702. get: function () {
  21703. if (!this._gamepadManager) {
  21704. this._gamepadManager = new BABYLON.GamepadManager(this);
  21705. }
  21706. return this._gamepadManager;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21712. get: function () {
  21713. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21719. get: function () {
  21720. return this._useRightHandedSystem;
  21721. },
  21722. set: function (value) {
  21723. if (this._useRightHandedSystem === value) {
  21724. return;
  21725. }
  21726. this._useRightHandedSystem = value;
  21727. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Scene.prototype.setStepId = function (newStepId) {
  21733. this._currentStepId = newStepId;
  21734. };
  21735. ;
  21736. Scene.prototype.getStepId = function () {
  21737. return this._currentStepId;
  21738. };
  21739. ;
  21740. Scene.prototype.getInternalStep = function () {
  21741. return this._currentInternalStep;
  21742. };
  21743. ;
  21744. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21745. get: function () {
  21746. return this._fogEnabled;
  21747. },
  21748. /**
  21749. * is fog enabled on this scene.
  21750. */
  21751. set: function (value) {
  21752. if (this._fogEnabled === value) {
  21753. return;
  21754. }
  21755. this._fogEnabled = value;
  21756. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Scene.prototype, "fogMode", {
  21762. get: function () {
  21763. return this._fogMode;
  21764. },
  21765. set: function (value) {
  21766. if (this._fogMode === value) {
  21767. return;
  21768. }
  21769. this._fogMode = value;
  21770. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21776. get: function () {
  21777. return this._shadowsEnabled;
  21778. },
  21779. set: function (value) {
  21780. if (this._shadowsEnabled === value) {
  21781. return;
  21782. }
  21783. this._shadowsEnabled = value;
  21784. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21790. get: function () {
  21791. return this._lightsEnabled;
  21792. },
  21793. set: function (value) {
  21794. if (this._lightsEnabled === value) {
  21795. return;
  21796. }
  21797. this._lightsEnabled = value;
  21798. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21804. /** The default material used on meshes when no material is affected */
  21805. get: function () {
  21806. if (!this._defaultMaterial) {
  21807. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21808. }
  21809. return this._defaultMaterial;
  21810. },
  21811. /** The default material used on meshes when no material is affected */
  21812. set: function (value) {
  21813. this._defaultMaterial = value;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21819. get: function () {
  21820. return this._texturesEnabled;
  21821. },
  21822. set: function (value) {
  21823. if (this._texturesEnabled === value) {
  21824. return;
  21825. }
  21826. this._texturesEnabled = value;
  21827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21833. get: function () {
  21834. return this._skeletonsEnabled;
  21835. },
  21836. set: function (value) {
  21837. if (this._skeletonsEnabled === value) {
  21838. return;
  21839. }
  21840. this._skeletonsEnabled = value;
  21841. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21842. },
  21843. enumerable: true,
  21844. configurable: true
  21845. });
  21846. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21847. get: function () {
  21848. if (!this._postProcessRenderPipelineManager) {
  21849. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21850. }
  21851. return this._postProcessRenderPipelineManager;
  21852. },
  21853. enumerable: true,
  21854. configurable: true
  21855. });
  21856. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21857. get: function () {
  21858. if (!this._mainSoundTrack) {
  21859. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21860. }
  21861. return this._mainSoundTrack;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21867. get: function () {
  21868. return this._alternateRendering;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21874. get: function () {
  21875. return this._frustumPlanes;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21881. /**
  21882. * Gets the current geometry buffer associated to the scene.
  21883. */
  21884. get: function () {
  21885. return this._geometryBufferRenderer;
  21886. },
  21887. /**
  21888. * Sets the current geometry buffer for the scene.
  21889. */
  21890. set: function (geometryBufferRenderer) {
  21891. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21892. this._geometryBufferRenderer = geometryBufferRenderer;
  21893. }
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Object.defineProperty(Scene.prototype, "debugLayer", {
  21899. // Properties
  21900. get: function () {
  21901. if (!this._debugLayer) {
  21902. this._debugLayer = new BABYLON.DebugLayer(this);
  21903. }
  21904. return this._debugLayer;
  21905. },
  21906. enumerable: true,
  21907. configurable: true
  21908. });
  21909. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21910. get: function () {
  21911. return this._workerCollisions;
  21912. },
  21913. set: function (enabled) {
  21914. if (!BABYLON.CollisionCoordinatorLegacy) {
  21915. return;
  21916. }
  21917. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21918. this._workerCollisions = enabled;
  21919. if (this.collisionCoordinator) {
  21920. this.collisionCoordinator.destroy();
  21921. }
  21922. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21923. this.collisionCoordinator.init(this);
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21929. get: function () {
  21930. return this._selectionOctree;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21936. /**
  21937. * The mesh that is currently under the pointer.
  21938. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21939. */
  21940. get: function () {
  21941. return this._pointerOverMesh;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. Object.defineProperty(Scene.prototype, "pointerX", {
  21947. /**
  21948. * Current on-screen X position of the pointer
  21949. * @return {number} X position of the pointer
  21950. */
  21951. get: function () {
  21952. return this._pointerX;
  21953. },
  21954. enumerable: true,
  21955. configurable: true
  21956. });
  21957. Object.defineProperty(Scene.prototype, "pointerY", {
  21958. /**
  21959. * Current on-screen Y position of the pointer
  21960. * @return {number} Y position of the pointer
  21961. */
  21962. get: function () {
  21963. return this._pointerY;
  21964. },
  21965. enumerable: true,
  21966. configurable: true
  21967. });
  21968. Scene.prototype.getCachedMaterial = function () {
  21969. return this._cachedMaterial;
  21970. };
  21971. Scene.prototype.getCachedEffect = function () {
  21972. return this._cachedEffect;
  21973. };
  21974. Scene.prototype.getCachedVisibility = function () {
  21975. return this._cachedVisibility;
  21976. };
  21977. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21978. if (visibility === void 0) { visibility = 1; }
  21979. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21980. };
  21981. Scene.prototype.getBoundingBoxRenderer = function () {
  21982. if (!this._boundingBoxRenderer) {
  21983. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21984. }
  21985. return this._boundingBoxRenderer;
  21986. };
  21987. Scene.prototype.getOutlineRenderer = function () {
  21988. return this._outlineRenderer;
  21989. };
  21990. Scene.prototype.getEngine = function () {
  21991. return this._engine;
  21992. };
  21993. Scene.prototype.getTotalVertices = function () {
  21994. return this._totalVertices.current;
  21995. };
  21996. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21997. get: function () {
  21998. return this._totalVertices;
  21999. },
  22000. enumerable: true,
  22001. configurable: true
  22002. });
  22003. Scene.prototype.getActiveIndices = function () {
  22004. return this._activeIndices.current;
  22005. };
  22006. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22007. get: function () {
  22008. return this._activeIndices;
  22009. },
  22010. enumerable: true,
  22011. configurable: true
  22012. });
  22013. Scene.prototype.getActiveParticles = function () {
  22014. return this._activeParticles.current;
  22015. };
  22016. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22017. get: function () {
  22018. return this._activeParticles;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Scene.prototype.getActiveBones = function () {
  22024. return this._activeBones.current;
  22025. };
  22026. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22027. get: function () {
  22028. return this._activeBones;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. // Stats
  22034. Scene.prototype.getInterFramePerfCounter = function () {
  22035. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22036. return 0;
  22037. };
  22038. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22039. get: function () {
  22040. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22041. return null;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. Scene.prototype.getLastFrameDuration = function () {
  22047. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22048. return 0;
  22049. };
  22050. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22051. get: function () {
  22052. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22053. return null;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22059. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22060. return 0;
  22061. };
  22062. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22063. get: function () {
  22064. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22065. return null;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Scene.prototype.getActiveMeshes = function () {
  22071. return this._activeMeshes;
  22072. };
  22073. Scene.prototype.getRenderTargetsDuration = function () {
  22074. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22075. return 0;
  22076. };
  22077. Scene.prototype.getRenderDuration = function () {
  22078. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22079. return 0;
  22080. };
  22081. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22082. get: function () {
  22083. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22084. return null;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Scene.prototype.getParticlesDuration = function () {
  22090. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22091. return 0;
  22092. };
  22093. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22094. get: function () {
  22095. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22096. return null;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. Scene.prototype.getSpritesDuration = function () {
  22102. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22103. return 0;
  22104. };
  22105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22106. get: function () {
  22107. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22108. return null;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Scene.prototype.getAnimationRatio = function () {
  22114. return this._animationRatio;
  22115. };
  22116. Scene.prototype.getRenderId = function () {
  22117. return this._renderId;
  22118. };
  22119. Scene.prototype.incrementRenderId = function () {
  22120. this._renderId++;
  22121. };
  22122. Scene.prototype._updatePointerPosition = function (evt) {
  22123. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22124. if (!canvasRect) {
  22125. return;
  22126. }
  22127. this._pointerX = evt.clientX - canvasRect.left;
  22128. this._pointerY = evt.clientY - canvasRect.top;
  22129. this._unTranslatedPointerX = this._pointerX;
  22130. this._unTranslatedPointerY = this._pointerY;
  22131. };
  22132. Scene.prototype._createUbo = function () {
  22133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22134. this._sceneUbo.addUniform("viewProjection", 16);
  22135. this._sceneUbo.addUniform("view", 16);
  22136. };
  22137. Scene.prototype._createAlternateUbo = function () {
  22138. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22139. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22140. this._alternateSceneUbo.addUniform("view", 16);
  22141. };
  22142. // Pointers handling
  22143. /**
  22144. * Use this method to simulate a pointer move on a mesh
  22145. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22146. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22147. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22148. */
  22149. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22150. var evt = new PointerEvent("pointermove", pointerEventInit);
  22151. return this._processPointerMove(pickResult, evt);
  22152. };
  22153. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22154. var canvas = this._engine.getRenderingCanvas();
  22155. if (!canvas) {
  22156. return this;
  22157. }
  22158. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22159. this.setPointerOverSprite(null);
  22160. this.setPointerOverMesh(pickResult.pickedMesh);
  22161. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22162. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22163. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22164. }
  22165. else {
  22166. canvas.style.cursor = this.hoverCursor;
  22167. }
  22168. }
  22169. else {
  22170. canvas.style.cursor = this.defaultCursor;
  22171. }
  22172. }
  22173. else {
  22174. this.setPointerOverMesh(null);
  22175. // Sprites
  22176. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22177. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22178. this.setPointerOverSprite(pickResult.pickedSprite);
  22179. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22180. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22181. }
  22182. else {
  22183. canvas.style.cursor = this.hoverCursor;
  22184. }
  22185. }
  22186. else {
  22187. this.setPointerOverSprite(null);
  22188. // Restore pointer
  22189. canvas.style.cursor = this.defaultCursor;
  22190. }
  22191. }
  22192. if (pickResult) {
  22193. if (this.onPointerMove) {
  22194. this.onPointerMove(evt, pickResult);
  22195. }
  22196. if (this.onPointerObservable.hasObservers()) {
  22197. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22198. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22199. this.onPointerObservable.notifyObservers(pi, type);
  22200. }
  22201. }
  22202. return this;
  22203. };
  22204. /**
  22205. * Use this method to simulate a pointer down on a mesh
  22206. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22207. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22208. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22209. */
  22210. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22211. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22212. return this._processPointerDown(pickResult, evt);
  22213. };
  22214. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22215. var _this = this;
  22216. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22217. this._pickedDownMesh = pickResult.pickedMesh;
  22218. var actionManager = pickResult.pickedMesh.actionManager;
  22219. if (actionManager) {
  22220. if (actionManager.hasPickTriggers) {
  22221. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22222. switch (evt.button) {
  22223. case 0:
  22224. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22225. break;
  22226. case 1:
  22227. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22228. break;
  22229. case 2:
  22230. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22231. break;
  22232. }
  22233. }
  22234. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22235. window.setTimeout(function () {
  22236. 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);
  22237. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22238. if (_this._totalPointersPressed !== 0 &&
  22239. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22240. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22241. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22242. _this._startingPointerTime = 0;
  22243. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22244. }
  22245. }
  22246. }, Scene.LongPressDelay);
  22247. }
  22248. }
  22249. }
  22250. if (pickResult) {
  22251. if (this.onPointerDown) {
  22252. this.onPointerDown(evt, pickResult);
  22253. }
  22254. if (this.onPointerObservable.hasObservers()) {
  22255. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22256. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22257. this.onPointerObservable.notifyObservers(pi, type);
  22258. }
  22259. }
  22260. return this;
  22261. };
  22262. /**
  22263. * Use this method to simulate a pointer up on a mesh
  22264. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22265. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22266. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22267. */
  22268. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22269. var evt = new PointerEvent("pointerup", pointerEventInit);
  22270. var clickInfo = new ClickInfo();
  22271. clickInfo.singleClick = true;
  22272. clickInfo.ignore = true;
  22273. return this._processPointerUp(pickResult, evt, clickInfo);
  22274. };
  22275. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22276. if (pickResult && pickResult && pickResult.pickedMesh) {
  22277. this._pickedUpMesh = pickResult.pickedMesh;
  22278. if (this._pickedDownMesh === this._pickedUpMesh) {
  22279. if (this.onPointerPick) {
  22280. this.onPointerPick(evt, pickResult);
  22281. }
  22282. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22283. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22284. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22285. this.onPointerObservable.notifyObservers(pi, type);
  22286. }
  22287. }
  22288. if (pickResult.pickedMesh.actionManager) {
  22289. if (clickInfo.ignore) {
  22290. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22291. }
  22292. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22293. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22294. }
  22295. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22296. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22297. }
  22298. }
  22299. }
  22300. if (this._pickedDownMesh &&
  22301. this._pickedDownMesh.actionManager &&
  22302. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22303. this._pickedDownMesh !== this._pickedUpMesh) {
  22304. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22305. }
  22306. if (this.onPointerUp) {
  22307. this.onPointerUp(evt, pickResult);
  22308. }
  22309. if (this.onPointerObservable.hasObservers()) {
  22310. if (!clickInfo.ignore) {
  22311. if (!clickInfo.hasSwiped) {
  22312. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22313. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22314. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22315. this.onPointerObservable.notifyObservers(pi, type);
  22316. }
  22317. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22318. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22319. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22320. this.onPointerObservable.notifyObservers(pi, type);
  22321. }
  22322. }
  22323. }
  22324. else {
  22325. var type = BABYLON.PointerEventTypes.POINTERUP;
  22326. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22327. this.onPointerObservable.notifyObservers(pi, type);
  22328. }
  22329. }
  22330. return this;
  22331. };
  22332. /**
  22333. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22334. * @param attachUp defines if you want to attach events to pointerup
  22335. * @param attachDown defines if you want to attach events to pointerdown
  22336. * @param attachMove defines if you want to attach events to pointermove
  22337. */
  22338. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22339. var _this = this;
  22340. if (attachUp === void 0) { attachUp = true; }
  22341. if (attachDown === void 0) { attachDown = true; }
  22342. if (attachMove === void 0) { attachMove = true; }
  22343. this._initActionManager = function (act, clickInfo) {
  22344. if (!_this._meshPickProceed) {
  22345. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22346. _this._currentPickResult = pickResult;
  22347. if (pickResult) {
  22348. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22349. }
  22350. _this._meshPickProceed = true;
  22351. }
  22352. return act;
  22353. };
  22354. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22355. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22356. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22357. btn !== _this._previousButtonPressed) {
  22358. _this._doubleClickOccured = false;
  22359. clickInfo.singleClick = true;
  22360. clickInfo.ignore = false;
  22361. cb(clickInfo, _this._currentPickResult);
  22362. }
  22363. };
  22364. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22365. var clickInfo = new ClickInfo();
  22366. _this._currentPickResult = null;
  22367. var act = null;
  22368. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22369. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22370. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22371. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22372. act = _this._initActionManager(act, clickInfo);
  22373. if (act)
  22374. checkPicking = act.hasPickTriggers;
  22375. }
  22376. if (checkPicking) {
  22377. var btn = evt.button;
  22378. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22379. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22380. if (!clickInfo.hasSwiped) {
  22381. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22382. if (!checkSingleClickImmediately) {
  22383. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22384. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22385. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22386. act = _this._initActionManager(act, clickInfo);
  22387. if (act)
  22388. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22389. }
  22390. }
  22391. if (checkSingleClickImmediately) {
  22392. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22393. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22394. btn !== _this._previousButtonPressed) {
  22395. clickInfo.singleClick = true;
  22396. cb(clickInfo, _this._currentPickResult);
  22397. }
  22398. }
  22399. else {
  22400. // wait that no double click has been raised during the double click delay
  22401. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22402. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22403. }
  22404. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22405. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22406. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22407. act = _this._initActionManager(act, clickInfo);
  22408. if (act)
  22409. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22410. }
  22411. if (checkDoubleClick) {
  22412. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22413. if (btn === _this._previousButtonPressed &&
  22414. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22415. !_this._doubleClickOccured) {
  22416. // pointer has not moved for 2 clicks, it's a double click
  22417. if (!clickInfo.hasSwiped &&
  22418. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22419. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22420. _this._previousStartingPointerTime = 0;
  22421. _this._doubleClickOccured = true;
  22422. clickInfo.doubleClick = true;
  22423. clickInfo.ignore = false;
  22424. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22425. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22426. }
  22427. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22428. cb(clickInfo, _this._currentPickResult);
  22429. }
  22430. else {
  22431. _this._doubleClickOccured = false;
  22432. _this._previousStartingPointerTime = _this._startingPointerTime;
  22433. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22434. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22435. _this._previousButtonPressed = btn;
  22436. if (Scene.ExclusiveDoubleClickMode) {
  22437. if (_this._previousDelayedSimpleClickTimeout) {
  22438. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22439. }
  22440. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22441. cb(clickInfo, _this._previousPickResult);
  22442. }
  22443. else {
  22444. cb(clickInfo, _this._currentPickResult);
  22445. }
  22446. }
  22447. }
  22448. else {
  22449. _this._doubleClickOccured = false;
  22450. _this._previousStartingPointerTime = _this._startingPointerTime;
  22451. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22452. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22453. _this._previousButtonPressed = btn;
  22454. }
  22455. }
  22456. }
  22457. }
  22458. clickInfo.ignore = true;
  22459. cb(clickInfo, _this._currentPickResult);
  22460. };
  22461. this._spritePredicate = function (sprite) {
  22462. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22463. };
  22464. this._onPointerMove = function (evt) {
  22465. _this._updatePointerPosition(evt);
  22466. // PreObservable support
  22467. if (_this.onPrePointerObservable.hasObservers()) {
  22468. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22469. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22470. _this.onPrePointerObservable.notifyObservers(pi, type);
  22471. if (pi.skipOnPointerObservable) {
  22472. return;
  22473. }
  22474. }
  22475. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22476. return;
  22477. }
  22478. if (!_this.pointerMovePredicate) {
  22479. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22480. }
  22481. // Meshes
  22482. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22483. _this._processPointerMove(pickResult, evt);
  22484. };
  22485. this._onPointerDown = function (evt) {
  22486. _this._totalPointersPressed++;
  22487. _this._pickedDownMesh = null;
  22488. _this._meshPickProceed = false;
  22489. _this._updatePointerPosition(evt);
  22490. if (_this.preventDefaultOnPointerDown && canvas) {
  22491. evt.preventDefault();
  22492. canvas.focus();
  22493. }
  22494. // PreObservable support
  22495. if (_this.onPrePointerObservable.hasObservers()) {
  22496. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22497. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22498. _this.onPrePointerObservable.notifyObservers(pi, type);
  22499. if (pi.skipOnPointerObservable) {
  22500. return;
  22501. }
  22502. }
  22503. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22504. return;
  22505. }
  22506. _this._startingPointerPosition.x = _this._pointerX;
  22507. _this._startingPointerPosition.y = _this._pointerY;
  22508. _this._startingPointerTime = new Date().getTime();
  22509. if (!_this.pointerDownPredicate) {
  22510. _this.pointerDownPredicate = function (mesh) {
  22511. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22512. };
  22513. }
  22514. // Meshes
  22515. _this._pickedDownMesh = null;
  22516. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22517. _this._processPointerDown(pickResult, evt);
  22518. // Sprites
  22519. _this._pickedDownSprite = null;
  22520. if (_this.spriteManagers.length > 0) {
  22521. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22522. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22523. if (pickResult.pickedSprite.actionManager) {
  22524. _this._pickedDownSprite = pickResult.pickedSprite;
  22525. switch (evt.button) {
  22526. case 0:
  22527. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22528. break;
  22529. case 1:
  22530. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22531. break;
  22532. case 2:
  22533. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22534. break;
  22535. }
  22536. if (pickResult.pickedSprite.actionManager) {
  22537. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22538. }
  22539. }
  22540. }
  22541. }
  22542. };
  22543. this._onPointerUp = function (evt) {
  22544. if (_this._totalPointersPressed === 0) {
  22545. return; // So we need to test it the pointer down was pressed before.
  22546. }
  22547. _this._totalPointersPressed--;
  22548. _this._pickedUpMesh = null;
  22549. _this._meshPickProceed = false;
  22550. _this._updatePointerPosition(evt);
  22551. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22552. // PreObservable support
  22553. if (_this.onPrePointerObservable.hasObservers()) {
  22554. if (!clickInfo.ignore) {
  22555. if (!clickInfo.hasSwiped) {
  22556. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22557. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22558. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22559. _this.onPrePointerObservable.notifyObservers(pi, type);
  22560. if (pi.skipOnPointerObservable) {
  22561. return;
  22562. }
  22563. }
  22564. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22565. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22566. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22567. _this.onPrePointerObservable.notifyObservers(pi, type);
  22568. if (pi.skipOnPointerObservable) {
  22569. return;
  22570. }
  22571. }
  22572. }
  22573. }
  22574. else {
  22575. var type = BABYLON.PointerEventTypes.POINTERUP;
  22576. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22577. _this.onPrePointerObservable.notifyObservers(pi, type);
  22578. if (pi.skipOnPointerObservable) {
  22579. return;
  22580. }
  22581. }
  22582. }
  22583. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22584. return;
  22585. }
  22586. if (!_this.pointerUpPredicate) {
  22587. _this.pointerUpPredicate = function (mesh) {
  22588. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22589. };
  22590. }
  22591. // Meshes
  22592. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22593. _this._initActionManager(null, clickInfo);
  22594. }
  22595. if (!pickResult) {
  22596. pickResult = _this._currentPickResult;
  22597. }
  22598. _this._processPointerUp(pickResult, evt, clickInfo);
  22599. // Sprites
  22600. if (_this.spriteManagers.length > 0) {
  22601. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22602. if (spritePickResult) {
  22603. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22604. if (spritePickResult.pickedSprite.actionManager) {
  22605. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22606. if (spritePickResult.pickedSprite.actionManager) {
  22607. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22608. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22609. }
  22610. }
  22611. }
  22612. }
  22613. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22614. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22615. }
  22616. }
  22617. }
  22618. _this._previousPickResult = _this._currentPickResult;
  22619. });
  22620. };
  22621. this._onKeyDown = function (evt) {
  22622. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22623. if (_this.onPreKeyboardObservable.hasObservers()) {
  22624. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22625. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22626. if (pi.skipOnPointerObservable) {
  22627. return;
  22628. }
  22629. }
  22630. if (_this.onKeyboardObservable.hasObservers()) {
  22631. var pi = new BABYLON.KeyboardInfo(type, evt);
  22632. _this.onKeyboardObservable.notifyObservers(pi, type);
  22633. }
  22634. if (_this.actionManager) {
  22635. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22636. }
  22637. };
  22638. this._onKeyUp = function (evt) {
  22639. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22640. if (_this.onPreKeyboardObservable.hasObservers()) {
  22641. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22642. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22643. if (pi.skipOnPointerObservable) {
  22644. return;
  22645. }
  22646. }
  22647. if (_this.onKeyboardObservable.hasObservers()) {
  22648. var pi = new BABYLON.KeyboardInfo(type, evt);
  22649. _this.onKeyboardObservable.notifyObservers(pi, type);
  22650. }
  22651. if (_this.actionManager) {
  22652. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22653. }
  22654. };
  22655. var engine = this.getEngine();
  22656. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22657. if (!canvas) {
  22658. return;
  22659. }
  22660. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22661. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22662. });
  22663. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22664. if (!canvas) {
  22665. return;
  22666. }
  22667. canvas.removeEventListener("keydown", _this._onKeyDown);
  22668. canvas.removeEventListener("keyup", _this._onKeyUp);
  22669. });
  22670. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22671. var canvas = this._engine.getRenderingCanvas();
  22672. if (!canvas) {
  22673. return;
  22674. }
  22675. if (attachMove) {
  22676. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22677. // Wheel
  22678. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22679. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22680. }
  22681. if (attachDown) {
  22682. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22683. }
  22684. if (attachUp) {
  22685. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22686. }
  22687. canvas.tabIndex = 1;
  22688. };
  22689. Scene.prototype.detachControl = function () {
  22690. var engine = this.getEngine();
  22691. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22692. var canvas = engine.getRenderingCanvas();
  22693. if (!canvas) {
  22694. return;
  22695. }
  22696. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22697. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22698. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22699. if (this._onCanvasBlurObserver) {
  22700. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22701. }
  22702. if (this._onCanvasFocusObserver) {
  22703. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22704. }
  22705. // Wheel
  22706. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22707. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22708. // Keyboard
  22709. canvas.removeEventListener("keydown", this._onKeyDown);
  22710. canvas.removeEventListener("keyup", this._onKeyUp);
  22711. // Observables
  22712. this.onKeyboardObservable.clear();
  22713. this.onPreKeyboardObservable.clear();
  22714. this.onPointerObservable.clear();
  22715. this.onPrePointerObservable.clear();
  22716. };
  22717. /**
  22718. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22719. * Delay loaded resources are not taking in account
  22720. * @return true if all required resources are ready
  22721. */
  22722. Scene.prototype.isReady = function () {
  22723. if (this._isDisposed) {
  22724. return false;
  22725. }
  22726. if (this._pendingData.length > 0) {
  22727. return false;
  22728. }
  22729. var index;
  22730. var engine = this.getEngine();
  22731. // Geometries
  22732. for (index = 0; index < this._geometries.length; index++) {
  22733. var geometry = this._geometries[index];
  22734. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22735. return false;
  22736. }
  22737. }
  22738. // Meshes
  22739. for (index = 0; index < this.meshes.length; index++) {
  22740. var mesh = this.meshes[index];
  22741. if (!mesh.isEnabled()) {
  22742. continue;
  22743. }
  22744. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22745. continue;
  22746. }
  22747. if (!mesh.isReady(true)) {
  22748. return false;
  22749. }
  22750. // Effect layers
  22751. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22752. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22753. var layer = _a[_i];
  22754. if (!layer.hasMesh(mesh)) {
  22755. continue;
  22756. }
  22757. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22758. var subMesh = _c[_b];
  22759. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22760. return false;
  22761. }
  22762. }
  22763. }
  22764. }
  22765. return true;
  22766. };
  22767. Scene.prototype.resetCachedMaterial = function () {
  22768. this._cachedMaterial = null;
  22769. this._cachedEffect = null;
  22770. this._cachedVisibility = null;
  22771. };
  22772. Scene.prototype.registerBeforeRender = function (func) {
  22773. this.onBeforeRenderObservable.add(func);
  22774. };
  22775. Scene.prototype.unregisterBeforeRender = function (func) {
  22776. this.onBeforeRenderObservable.removeCallback(func);
  22777. };
  22778. Scene.prototype.registerAfterRender = function (func) {
  22779. this.onAfterRenderObservable.add(func);
  22780. };
  22781. Scene.prototype.unregisterAfterRender = function (func) {
  22782. this.onAfterRenderObservable.removeCallback(func);
  22783. };
  22784. Scene.prototype._executeOnceBeforeRender = function (func) {
  22785. var _this = this;
  22786. var execFunc = function () {
  22787. func();
  22788. setTimeout(function () {
  22789. _this.unregisterBeforeRender(execFunc);
  22790. });
  22791. };
  22792. this.registerBeforeRender(execFunc);
  22793. };
  22794. /**
  22795. * The provided function will run before render once and will be disposed afterwards.
  22796. * A timeout delay can be provided so that the function will be executed in N ms.
  22797. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22798. * @param func The function to be executed.
  22799. * @param timeout optional delay in ms
  22800. */
  22801. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22802. var _this = this;
  22803. if (timeout !== undefined) {
  22804. setTimeout(function () {
  22805. _this._executeOnceBeforeRender(func);
  22806. }, timeout);
  22807. }
  22808. else {
  22809. this._executeOnceBeforeRender(func);
  22810. }
  22811. };
  22812. Scene.prototype._addPendingData = function (data) {
  22813. this._pendingData.push(data);
  22814. };
  22815. Scene.prototype._removePendingData = function (data) {
  22816. var wasLoading = this.isLoading;
  22817. var index = this._pendingData.indexOf(data);
  22818. if (index !== -1) {
  22819. this._pendingData.splice(index, 1);
  22820. }
  22821. if (wasLoading && !this.isLoading) {
  22822. this.onDataLoadedObservable.notifyObservers(this);
  22823. }
  22824. };
  22825. Scene.prototype.getWaitingItemsCount = function () {
  22826. return this._pendingData.length;
  22827. };
  22828. Object.defineProperty(Scene.prototype, "isLoading", {
  22829. get: function () {
  22830. return this._pendingData.length > 0;
  22831. },
  22832. enumerable: true,
  22833. configurable: true
  22834. });
  22835. /**
  22836. * Registers a function to be executed when the scene is ready.
  22837. * @param {Function} func - the function to be executed.
  22838. */
  22839. Scene.prototype.executeWhenReady = function (func) {
  22840. var _this = this;
  22841. this.onReadyObservable.add(func);
  22842. if (this._executeWhenReadyTimeoutId !== -1) {
  22843. return;
  22844. }
  22845. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22846. _this._checkIsReady();
  22847. }, 150);
  22848. };
  22849. /**
  22850. * Returns a promise that resolves when the scene is ready.
  22851. * @returns A promise that resolves when the scene is ready.
  22852. */
  22853. Scene.prototype.whenReadyAsync = function () {
  22854. var _this = this;
  22855. return new Promise(function (resolve) {
  22856. _this.executeWhenReady(function () {
  22857. resolve();
  22858. });
  22859. });
  22860. };
  22861. Scene.prototype._checkIsReady = function () {
  22862. var _this = this;
  22863. if (this.isReady()) {
  22864. this.onReadyObservable.notifyObservers(this);
  22865. this.onReadyObservable.clear();
  22866. this._executeWhenReadyTimeoutId = -1;
  22867. return;
  22868. }
  22869. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22870. _this._checkIsReady();
  22871. }, 150);
  22872. };
  22873. // Animations
  22874. /**
  22875. * Will start the animation sequence of a given target
  22876. * @param target - the target
  22877. * @param {number} from - from which frame should animation start
  22878. * @param {number} to - till which frame should animation run.
  22879. * @param {boolean} [loop] - should the animation loop
  22880. * @param {number} [speedRatio] - the speed in which to run the animation
  22881. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22882. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22883. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22884. * See BABYLON.Animatable
  22885. */
  22886. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22887. if (speedRatio === void 0) { speedRatio = 1.0; }
  22888. if (from > to && speedRatio > 0) {
  22889. speedRatio *= -1;
  22890. }
  22891. this.stopAnimation(target);
  22892. if (!animatable) {
  22893. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22894. }
  22895. // Local animations
  22896. if (target.animations) {
  22897. animatable.appendAnimations(target, target.animations);
  22898. }
  22899. // Children animations
  22900. if (target.getAnimatables) {
  22901. var animatables = target.getAnimatables();
  22902. for (var index = 0; index < animatables.length; index++) {
  22903. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22904. }
  22905. }
  22906. animatable.reset();
  22907. return animatable;
  22908. };
  22909. /**
  22910. * Begin a new animation on a given node
  22911. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22912. * @param {BABYLON.Animation[]} defines the list of animations to start
  22913. * @param {number} from defines the initial value
  22914. * @param {number} to defines the final value
  22915. * @param {boolean} loop defines if you want animation to loop (off by default)
  22916. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22917. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22918. * @returns the list of created animatables
  22919. */
  22920. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22921. if (speedRatio === undefined) {
  22922. speedRatio = 1.0;
  22923. }
  22924. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22925. return animatable;
  22926. };
  22927. /**
  22928. * Begin a new animation on a given node and its hierarchy
  22929. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22930. * @param {boolean} 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.
  22931. * @param {BABYLON.Animation[]} defines the list of animations to start
  22932. * @param {number} from defines the initial value
  22933. * @param {number} to defines the final value
  22934. * @param {boolean} loop defines if you want animation to loop (off by default)
  22935. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22936. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22937. * @returns the list of animatables created for all nodes
  22938. */
  22939. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22940. var children = target.getDescendants(directDescendantsOnly);
  22941. var result = [];
  22942. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22943. var child = children_1[_i];
  22944. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22945. }
  22946. return result;
  22947. };
  22948. Scene.prototype.getAnimatableByTarget = function (target) {
  22949. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22950. if (this._activeAnimatables[index].target === target) {
  22951. return this._activeAnimatables[index];
  22952. }
  22953. }
  22954. return null;
  22955. };
  22956. Object.defineProperty(Scene.prototype, "animatables", {
  22957. get: function () {
  22958. return this._activeAnimatables;
  22959. },
  22960. enumerable: true,
  22961. configurable: true
  22962. });
  22963. /**
  22964. * Will stop the animation of the given target
  22965. * @param target - the target
  22966. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22967. * @see beginAnimation
  22968. */
  22969. Scene.prototype.stopAnimation = function (target, animationName) {
  22970. var animatable = this.getAnimatableByTarget(target);
  22971. if (animatable) {
  22972. animatable.stop(animationName);
  22973. }
  22974. };
  22975. /**
  22976. * Stops and removes all animations that have been applied to the scene
  22977. */
  22978. Scene.prototype.stopAllAnimations = function () {
  22979. if (this._activeAnimatables) {
  22980. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22981. this._activeAnimatables[i].stop();
  22982. }
  22983. this._activeAnimatables = [];
  22984. }
  22985. };
  22986. Scene.prototype._animate = function () {
  22987. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22988. return;
  22989. }
  22990. // Getting time
  22991. var now = BABYLON.Tools.Now;
  22992. if (!this._animationTimeLast) {
  22993. if (this._pendingData.length > 0) {
  22994. return;
  22995. }
  22996. this._animationTimeLast = now;
  22997. }
  22998. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22999. this._animationTime += deltaTime;
  23000. this._animationTimeLast = now;
  23001. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23002. this._activeAnimatables[index]._animate(this._animationTime);
  23003. }
  23004. };
  23005. // Matrix
  23006. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23007. this._useAlternateCameraConfiguration = active;
  23008. };
  23009. Scene.prototype.getViewMatrix = function () {
  23010. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23011. };
  23012. Scene.prototype.getProjectionMatrix = function () {
  23013. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23014. };
  23015. Scene.prototype.getTransformMatrix = function () {
  23016. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23017. };
  23018. Scene.prototype.setTransformMatrix = function (view, projection) {
  23019. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23020. return;
  23021. }
  23022. this._viewUpdateFlag = view.updateFlag;
  23023. this._projectionUpdateFlag = projection.updateFlag;
  23024. this._viewMatrix = view;
  23025. this._projectionMatrix = projection;
  23026. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23027. // Update frustum
  23028. if (!this._frustumPlanes) {
  23029. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23030. }
  23031. else {
  23032. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23033. }
  23034. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23035. var otherCamera = this.activeCamera._alternateCamera;
  23036. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23037. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23038. }
  23039. if (this._sceneUbo.useUbo) {
  23040. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23041. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23042. this._sceneUbo.update();
  23043. }
  23044. };
  23045. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23046. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23047. return;
  23048. }
  23049. this._alternateViewUpdateFlag = view.updateFlag;
  23050. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23051. this._alternateViewMatrix = view;
  23052. this._alternateProjectionMatrix = projection;
  23053. if (!this._alternateTransformMatrix) {
  23054. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23055. }
  23056. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23057. if (!this._alternateSceneUbo) {
  23058. this._createAlternateUbo();
  23059. }
  23060. if (this._alternateSceneUbo.useUbo) {
  23061. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23062. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23063. this._alternateSceneUbo.update();
  23064. }
  23065. };
  23066. Scene.prototype.getSceneUniformBuffer = function () {
  23067. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23068. };
  23069. // Methods
  23070. Scene.prototype.getUniqueId = function () {
  23071. var result = Scene._uniqueIdCounter;
  23072. Scene._uniqueIdCounter++;
  23073. return result;
  23074. };
  23075. Scene.prototype.addMesh = function (newMesh) {
  23076. this.meshes.push(newMesh);
  23077. //notify the collision coordinator
  23078. if (this.collisionCoordinator) {
  23079. this.collisionCoordinator.onMeshAdded(newMesh);
  23080. }
  23081. newMesh._resyncLightSources();
  23082. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23083. };
  23084. Scene.prototype.removeMesh = function (toRemove) {
  23085. var index = this.meshes.indexOf(toRemove);
  23086. if (index !== -1) {
  23087. // Remove from the scene if mesh found
  23088. this.meshes.splice(index, 1);
  23089. }
  23090. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23091. return index;
  23092. };
  23093. Scene.prototype.addTransformNode = function (newTransformNode) {
  23094. this.transformNodes.push(newTransformNode);
  23095. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23096. };
  23097. Scene.prototype.removeTransformNode = function (toRemove) {
  23098. var index = this.transformNodes.indexOf(toRemove);
  23099. if (index !== -1) {
  23100. // Remove from the scene if found
  23101. this.transformNodes.splice(index, 1);
  23102. }
  23103. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23104. return index;
  23105. };
  23106. Scene.prototype.removeSkeleton = function (toRemove) {
  23107. var index = this.skeletons.indexOf(toRemove);
  23108. if (index !== -1) {
  23109. // Remove from the scene if found
  23110. this.skeletons.splice(index, 1);
  23111. }
  23112. return index;
  23113. };
  23114. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23115. var index = this.morphTargetManagers.indexOf(toRemove);
  23116. if (index !== -1) {
  23117. // Remove from the scene if found
  23118. this.morphTargetManagers.splice(index, 1);
  23119. }
  23120. return index;
  23121. };
  23122. Scene.prototype.removeLight = function (toRemove) {
  23123. var index = this.lights.indexOf(toRemove);
  23124. if (index !== -1) {
  23125. // Remove from meshes
  23126. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23127. var mesh = _a[_i];
  23128. mesh._removeLightSource(toRemove);
  23129. }
  23130. // Remove from the scene if mesh found
  23131. this.lights.splice(index, 1);
  23132. this.sortLightsByPriority();
  23133. }
  23134. this.onLightRemovedObservable.notifyObservers(toRemove);
  23135. return index;
  23136. };
  23137. Scene.prototype.removeCamera = function (toRemove) {
  23138. var index = this.cameras.indexOf(toRemove);
  23139. if (index !== -1) {
  23140. // Remove from the scene if mesh found
  23141. this.cameras.splice(index, 1);
  23142. }
  23143. // Remove from activeCameras
  23144. var index2 = this.activeCameras.indexOf(toRemove);
  23145. if (index2 !== -1) {
  23146. // Remove from the scene if mesh found
  23147. this.activeCameras.splice(index2, 1);
  23148. }
  23149. // Reset the activeCamera
  23150. if (this.activeCamera === toRemove) {
  23151. if (this.cameras.length > 0) {
  23152. this.activeCamera = this.cameras[0];
  23153. }
  23154. else {
  23155. this.activeCamera = null;
  23156. }
  23157. }
  23158. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23159. return index;
  23160. };
  23161. Scene.prototype.removeParticleSystem = function (toRemove) {
  23162. var index = this.particleSystems.indexOf(toRemove);
  23163. if (index !== -1) {
  23164. this.particleSystems.splice(index, 1);
  23165. }
  23166. return index;
  23167. };
  23168. ;
  23169. Scene.prototype.removeAnimation = function (toRemove) {
  23170. var index = this.animations.indexOf(toRemove);
  23171. if (index !== -1) {
  23172. this.animations.splice(index, 1);
  23173. }
  23174. return index;
  23175. };
  23176. ;
  23177. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23178. var index = this.multiMaterials.indexOf(toRemove);
  23179. if (index !== -1) {
  23180. this.multiMaterials.splice(index, 1);
  23181. }
  23182. return index;
  23183. };
  23184. ;
  23185. Scene.prototype.removeMaterial = function (toRemove) {
  23186. var index = this.materials.indexOf(toRemove);
  23187. if (index !== -1) {
  23188. this.materials.splice(index, 1);
  23189. }
  23190. return index;
  23191. };
  23192. ;
  23193. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23194. var index = this.lensFlareSystems.indexOf(toRemove);
  23195. if (index !== -1) {
  23196. this.lensFlareSystems.splice(index, 1);
  23197. }
  23198. return index;
  23199. };
  23200. ;
  23201. Scene.prototype.removeActionManager = function (toRemove) {
  23202. var index = this._actionManagers.indexOf(toRemove);
  23203. if (index !== -1) {
  23204. this._actionManagers.splice(index, 1);
  23205. }
  23206. return index;
  23207. };
  23208. ;
  23209. Scene.prototype.addLight = function (newLight) {
  23210. this.lights.push(newLight);
  23211. this.sortLightsByPriority();
  23212. // Add light to all meshes (To support if the light is removed and then readded)
  23213. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23214. var mesh = _a[_i];
  23215. if (mesh._lightSources.indexOf(newLight) === -1) {
  23216. mesh._lightSources.push(newLight);
  23217. mesh._resyncLightSources();
  23218. }
  23219. }
  23220. this.onNewLightAddedObservable.notifyObservers(newLight);
  23221. };
  23222. Scene.prototype.sortLightsByPriority = function () {
  23223. if (this.requireLightSorting) {
  23224. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23225. }
  23226. };
  23227. Scene.prototype.addCamera = function (newCamera) {
  23228. this.cameras.push(newCamera);
  23229. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23230. };
  23231. Scene.prototype.addSkeleton = function (newSkeleton) {
  23232. this.skeletons.push(newSkeleton);
  23233. };
  23234. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23235. this.particleSystems.push(newParticleSystem);
  23236. };
  23237. Scene.prototype.addAnimation = function (newAnimation) {
  23238. this.animations.push(newAnimation);
  23239. };
  23240. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23241. this.multiMaterials.push(newMultiMaterial);
  23242. };
  23243. Scene.prototype.addMaterial = function (newMaterial) {
  23244. this.materials.push(newMaterial);
  23245. };
  23246. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23247. this.morphTargetManagers.push(newMorphTargetManager);
  23248. };
  23249. Scene.prototype.addGeometry = function (newGeometrie) {
  23250. this._geometries.push(newGeometrie);
  23251. };
  23252. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23253. this.lensFlareSystems.push(newLensFlareSystem);
  23254. };
  23255. Scene.prototype.addActionManager = function (newActionManager) {
  23256. this._actionManagers.push(newActionManager);
  23257. };
  23258. /**
  23259. * Switch active camera
  23260. * @param {Camera} newCamera - new active camera
  23261. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23262. */
  23263. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23264. if (attachControl === void 0) { attachControl = true; }
  23265. var canvas = this._engine.getRenderingCanvas();
  23266. if (!canvas) {
  23267. return;
  23268. }
  23269. if (this.activeCamera) {
  23270. this.activeCamera.detachControl(canvas);
  23271. }
  23272. this.activeCamera = newCamera;
  23273. if (attachControl) {
  23274. newCamera.attachControl(canvas);
  23275. }
  23276. };
  23277. /**
  23278. * sets the active camera of the scene using its ID
  23279. * @param {string} id - the camera's ID
  23280. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23281. * @see activeCamera
  23282. */
  23283. Scene.prototype.setActiveCameraByID = function (id) {
  23284. var camera = this.getCameraByID(id);
  23285. if (camera) {
  23286. this.activeCamera = camera;
  23287. return camera;
  23288. }
  23289. return null;
  23290. };
  23291. /**
  23292. * sets the active camera of the scene using its name
  23293. * @param {string} name - the camera's name
  23294. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23295. * @see activeCamera
  23296. */
  23297. Scene.prototype.setActiveCameraByName = function (name) {
  23298. var camera = this.getCameraByName(name);
  23299. if (camera) {
  23300. this.activeCamera = camera;
  23301. return camera;
  23302. }
  23303. return null;
  23304. };
  23305. /**
  23306. * get an animation group using its name
  23307. * @param {string} the material's name
  23308. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23309. */
  23310. Scene.prototype.getAnimationGroupByName = function (name) {
  23311. for (var index = 0; index < this.animationGroups.length; index++) {
  23312. if (this.animationGroups[index].name === name) {
  23313. return this.animationGroups[index];
  23314. }
  23315. }
  23316. return null;
  23317. };
  23318. /**
  23319. * get a material using its id
  23320. * @param {string} the material's ID
  23321. * @return {BABYLON.Material|null} the material or null if none found.
  23322. */
  23323. Scene.prototype.getMaterialByID = function (id) {
  23324. for (var index = 0; index < this.materials.length; index++) {
  23325. if (this.materials[index].id === id) {
  23326. return this.materials[index];
  23327. }
  23328. }
  23329. return null;
  23330. };
  23331. /**
  23332. * get a material using its name
  23333. * @param {string} the material's name
  23334. * @return {BABYLON.Material|null} the material or null if none found.
  23335. */
  23336. Scene.prototype.getMaterialByName = function (name) {
  23337. for (var index = 0; index < this.materials.length; index++) {
  23338. if (this.materials[index].name === name) {
  23339. return this.materials[index];
  23340. }
  23341. }
  23342. return null;
  23343. };
  23344. Scene.prototype.getLensFlareSystemByName = function (name) {
  23345. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23346. if (this.lensFlareSystems[index].name === name) {
  23347. return this.lensFlareSystems[index];
  23348. }
  23349. }
  23350. return null;
  23351. };
  23352. Scene.prototype.getLensFlareSystemByID = function (id) {
  23353. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23354. if (this.lensFlareSystems[index].id === id) {
  23355. return this.lensFlareSystems[index];
  23356. }
  23357. }
  23358. return null;
  23359. };
  23360. Scene.prototype.getCameraByID = function (id) {
  23361. for (var index = 0; index < this.cameras.length; index++) {
  23362. if (this.cameras[index].id === id) {
  23363. return this.cameras[index];
  23364. }
  23365. }
  23366. return null;
  23367. };
  23368. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23369. for (var index = 0; index < this.cameras.length; index++) {
  23370. if (this.cameras[index].uniqueId === uniqueId) {
  23371. return this.cameras[index];
  23372. }
  23373. }
  23374. return null;
  23375. };
  23376. /**
  23377. * get a camera using its name
  23378. * @param {string} the camera's name
  23379. * @return {BABYLON.Camera|null} the camera or null if none found.
  23380. */
  23381. Scene.prototype.getCameraByName = function (name) {
  23382. for (var index = 0; index < this.cameras.length; index++) {
  23383. if (this.cameras[index].name === name) {
  23384. return this.cameras[index];
  23385. }
  23386. }
  23387. return null;
  23388. };
  23389. /**
  23390. * get a bone using its id
  23391. * @param {string} the bone's id
  23392. * @return {BABYLON.Bone|null} the bone or null if not found
  23393. */
  23394. Scene.prototype.getBoneByID = function (id) {
  23395. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23396. var skeleton = this.skeletons[skeletonIndex];
  23397. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23398. if (skeleton.bones[boneIndex].id === id) {
  23399. return skeleton.bones[boneIndex];
  23400. }
  23401. }
  23402. }
  23403. return null;
  23404. };
  23405. /**
  23406. * get a bone using its id
  23407. * @param {string} the bone's name
  23408. * @return {BABYLON.Bone|null} the bone or null if not found
  23409. */
  23410. Scene.prototype.getBoneByName = function (name) {
  23411. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23412. var skeleton = this.skeletons[skeletonIndex];
  23413. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23414. if (skeleton.bones[boneIndex].name === name) {
  23415. return skeleton.bones[boneIndex];
  23416. }
  23417. }
  23418. }
  23419. return null;
  23420. };
  23421. /**
  23422. * get a light node using its name
  23423. * @param {string} the light's name
  23424. * @return {BABYLON.Light|null} the light or null if none found.
  23425. */
  23426. Scene.prototype.getLightByName = function (name) {
  23427. for (var index = 0; index < this.lights.length; index++) {
  23428. if (this.lights[index].name === name) {
  23429. return this.lights[index];
  23430. }
  23431. }
  23432. return null;
  23433. };
  23434. /**
  23435. * get a light node using its ID
  23436. * @param {string} the light's id
  23437. * @return {BABYLON.Light|null} the light or null if none found.
  23438. */
  23439. Scene.prototype.getLightByID = function (id) {
  23440. for (var index = 0; index < this.lights.length; index++) {
  23441. if (this.lights[index].id === id) {
  23442. return this.lights[index];
  23443. }
  23444. }
  23445. return null;
  23446. };
  23447. /**
  23448. * get a light node using its scene-generated unique ID
  23449. * @param {number} the light's unique id
  23450. * @return {BABYLON.Light|null} the light or null if none found.
  23451. */
  23452. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23453. for (var index = 0; index < this.lights.length; index++) {
  23454. if (this.lights[index].uniqueId === uniqueId) {
  23455. return this.lights[index];
  23456. }
  23457. }
  23458. return null;
  23459. };
  23460. /**
  23461. * get a particle system by id
  23462. * @param id {number} the particle system id
  23463. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23464. */
  23465. Scene.prototype.getParticleSystemByID = function (id) {
  23466. for (var index = 0; index < this.particleSystems.length; index++) {
  23467. if (this.particleSystems[index].id === id) {
  23468. return this.particleSystems[index];
  23469. }
  23470. }
  23471. return null;
  23472. };
  23473. /**
  23474. * get a geometry using its ID
  23475. * @param {string} the geometry's id
  23476. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23477. */
  23478. Scene.prototype.getGeometryByID = function (id) {
  23479. for (var index = 0; index < this._geometries.length; index++) {
  23480. if (this._geometries[index].id === id) {
  23481. return this._geometries[index];
  23482. }
  23483. }
  23484. return null;
  23485. };
  23486. /**
  23487. * add a new geometry to this scene.
  23488. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23489. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23490. * @return {boolean} was the geometry added or not
  23491. */
  23492. Scene.prototype.pushGeometry = function (geometry, force) {
  23493. if (!force && this.getGeometryByID(geometry.id)) {
  23494. return false;
  23495. }
  23496. this._geometries.push(geometry);
  23497. //notify the collision coordinator
  23498. if (this.collisionCoordinator) {
  23499. this.collisionCoordinator.onGeometryAdded(geometry);
  23500. }
  23501. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23502. return true;
  23503. };
  23504. /**
  23505. * Removes an existing geometry
  23506. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23507. * @return {boolean} was the geometry removed or not
  23508. */
  23509. Scene.prototype.removeGeometry = function (geometry) {
  23510. var index = this._geometries.indexOf(geometry);
  23511. if (index > -1) {
  23512. this._geometries.splice(index, 1);
  23513. //notify the collision coordinator
  23514. if (this.collisionCoordinator) {
  23515. this.collisionCoordinator.onGeometryDeleted(geometry);
  23516. }
  23517. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23518. return true;
  23519. }
  23520. return false;
  23521. };
  23522. Scene.prototype.getGeometries = function () {
  23523. return this._geometries;
  23524. };
  23525. /**
  23526. * Get the first added mesh found of a given ID
  23527. * @param {string} id - the id to search for
  23528. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23529. */
  23530. Scene.prototype.getMeshByID = function (id) {
  23531. for (var index = 0; index < this.meshes.length; index++) {
  23532. if (this.meshes[index].id === id) {
  23533. return this.meshes[index];
  23534. }
  23535. }
  23536. return null;
  23537. };
  23538. Scene.prototype.getMeshesByID = function (id) {
  23539. return this.meshes.filter(function (m) {
  23540. return m.id === id;
  23541. });
  23542. };
  23543. /**
  23544. * Get the first added transform node found of a given ID
  23545. * @param {string} id - the id to search for
  23546. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23547. */
  23548. Scene.prototype.getTransformNodeByID = function (id) {
  23549. for (var index = 0; index < this.transformNodes.length; index++) {
  23550. if (this.transformNodes[index].id === id) {
  23551. return this.transformNodes[index];
  23552. }
  23553. }
  23554. return null;
  23555. };
  23556. Scene.prototype.getTransformNodesByID = function (id) {
  23557. return this.transformNodes.filter(function (m) {
  23558. return m.id === id;
  23559. });
  23560. };
  23561. /**
  23562. * Get a mesh with its auto-generated unique id
  23563. * @param {number} uniqueId - the unique id to search for
  23564. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23565. */
  23566. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23567. for (var index = 0; index < this.meshes.length; index++) {
  23568. if (this.meshes[index].uniqueId === uniqueId) {
  23569. return this.meshes[index];
  23570. }
  23571. }
  23572. return null;
  23573. };
  23574. /**
  23575. * Get a the last added mesh found of a given ID
  23576. * @param {string} id - the id to search for
  23577. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23578. */
  23579. Scene.prototype.getLastMeshByID = function (id) {
  23580. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23581. if (this.meshes[index].id === id) {
  23582. return this.meshes[index];
  23583. }
  23584. }
  23585. return null;
  23586. };
  23587. /**
  23588. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23589. * @param {string} id - the id to search for
  23590. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23591. */
  23592. Scene.prototype.getLastEntryByID = function (id) {
  23593. var index;
  23594. for (index = this.meshes.length - 1; index >= 0; index--) {
  23595. if (this.meshes[index].id === id) {
  23596. return this.meshes[index];
  23597. }
  23598. }
  23599. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23600. if (this.transformNodes[index].id === id) {
  23601. return this.transformNodes[index];
  23602. }
  23603. }
  23604. for (index = this.cameras.length - 1; index >= 0; index--) {
  23605. if (this.cameras[index].id === id) {
  23606. return this.cameras[index];
  23607. }
  23608. }
  23609. for (index = this.lights.length - 1; index >= 0; index--) {
  23610. if (this.lights[index].id === id) {
  23611. return this.lights[index];
  23612. }
  23613. }
  23614. return null;
  23615. };
  23616. Scene.prototype.getNodeByID = function (id) {
  23617. var mesh = this.getMeshByID(id);
  23618. if (mesh) {
  23619. return mesh;
  23620. }
  23621. var light = this.getLightByID(id);
  23622. if (light) {
  23623. return light;
  23624. }
  23625. var camera = this.getCameraByID(id);
  23626. if (camera) {
  23627. return camera;
  23628. }
  23629. var bone = this.getBoneByID(id);
  23630. return bone;
  23631. };
  23632. Scene.prototype.getNodeByName = function (name) {
  23633. var mesh = this.getMeshByName(name);
  23634. if (mesh) {
  23635. return mesh;
  23636. }
  23637. var light = this.getLightByName(name);
  23638. if (light) {
  23639. return light;
  23640. }
  23641. var camera = this.getCameraByName(name);
  23642. if (camera) {
  23643. return camera;
  23644. }
  23645. var bone = this.getBoneByName(name);
  23646. return bone;
  23647. };
  23648. Scene.prototype.getMeshByName = function (name) {
  23649. for (var index = 0; index < this.meshes.length; index++) {
  23650. if (this.meshes[index].name === name) {
  23651. return this.meshes[index];
  23652. }
  23653. }
  23654. return null;
  23655. };
  23656. Scene.prototype.getTransformNodeByName = function (name) {
  23657. for (var index = 0; index < this.transformNodes.length; index++) {
  23658. if (this.transformNodes[index].name === name) {
  23659. return this.transformNodes[index];
  23660. }
  23661. }
  23662. return null;
  23663. };
  23664. Scene.prototype.getSoundByName = function (name) {
  23665. var index;
  23666. if (BABYLON.AudioEngine) {
  23667. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23668. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23669. return this.mainSoundTrack.soundCollection[index];
  23670. }
  23671. }
  23672. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23673. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23674. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23675. return this.soundTracks[sdIndex].soundCollection[index];
  23676. }
  23677. }
  23678. }
  23679. }
  23680. return null;
  23681. };
  23682. Scene.prototype.getLastSkeletonByID = function (id) {
  23683. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23684. if (this.skeletons[index].id === id) {
  23685. return this.skeletons[index];
  23686. }
  23687. }
  23688. return null;
  23689. };
  23690. Scene.prototype.getSkeletonById = function (id) {
  23691. for (var index = 0; index < this.skeletons.length; index++) {
  23692. if (this.skeletons[index].id === id) {
  23693. return this.skeletons[index];
  23694. }
  23695. }
  23696. return null;
  23697. };
  23698. Scene.prototype.getSkeletonByName = function (name) {
  23699. for (var index = 0; index < this.skeletons.length; index++) {
  23700. if (this.skeletons[index].name === name) {
  23701. return this.skeletons[index];
  23702. }
  23703. }
  23704. return null;
  23705. };
  23706. Scene.prototype.getMorphTargetManagerById = function (id) {
  23707. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23708. if (this.morphTargetManagers[index].uniqueId === id) {
  23709. return this.morphTargetManagers[index];
  23710. }
  23711. }
  23712. return null;
  23713. };
  23714. Scene.prototype.isActiveMesh = function (mesh) {
  23715. return (this._activeMeshes.indexOf(mesh) !== -1);
  23716. };
  23717. /**
  23718. * Return a the first highlight layer of the scene with a given name.
  23719. * @param name The name of the highlight layer to look for.
  23720. * @return The highlight layer if found otherwise null.
  23721. */
  23722. Scene.prototype.getHighlightLayerByName = function (name) {
  23723. for (var index = 0; index < this.effectLayers.length; index++) {
  23724. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23725. return this.effectLayers[index];
  23726. }
  23727. }
  23728. return null;
  23729. };
  23730. /**
  23731. * Return a the first highlight layer of the scene with a given name.
  23732. * @param name The name of the highlight layer to look for.
  23733. * @return The highlight layer if found otherwise null.
  23734. */
  23735. Scene.prototype.getGlowLayerByName = function (name) {
  23736. for (var index = 0; index < this.effectLayers.length; index++) {
  23737. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23738. return this.effectLayers[index];
  23739. }
  23740. }
  23741. return null;
  23742. };
  23743. Object.defineProperty(Scene.prototype, "uid", {
  23744. /**
  23745. * Return a unique id as a string which can serve as an identifier for the scene
  23746. */
  23747. get: function () {
  23748. if (!this._uid) {
  23749. this._uid = BABYLON.Tools.RandomId();
  23750. }
  23751. return this._uid;
  23752. },
  23753. enumerable: true,
  23754. configurable: true
  23755. });
  23756. /**
  23757. * Add an externaly attached data from its key.
  23758. * This method call will fail and return false, if such key already exists.
  23759. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23760. * @param key the unique key that identifies the data
  23761. * @param data the data object to associate to the key for this Engine instance
  23762. * @return true if no such key were already present and the data was added successfully, false otherwise
  23763. */
  23764. Scene.prototype.addExternalData = function (key, data) {
  23765. if (!this._externalData) {
  23766. this._externalData = new BABYLON.StringDictionary();
  23767. }
  23768. return this._externalData.add(key, data);
  23769. };
  23770. /**
  23771. * Get an externaly attached data from its key
  23772. * @param key the unique key that identifies the data
  23773. * @return the associated data, if present (can be null), or undefined if not present
  23774. */
  23775. Scene.prototype.getExternalData = function (key) {
  23776. if (!this._externalData) {
  23777. return null;
  23778. }
  23779. return this._externalData.get(key);
  23780. };
  23781. /**
  23782. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23783. * @param key the unique key that identifies the data
  23784. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23785. * @return the associated data, can be null if the factory returned null.
  23786. */
  23787. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23788. if (!this._externalData) {
  23789. this._externalData = new BABYLON.StringDictionary();
  23790. }
  23791. return this._externalData.getOrAddWithFactory(key, factory);
  23792. };
  23793. /**
  23794. * Remove an externaly attached data from the Engine instance
  23795. * @param key the unique key that identifies the data
  23796. * @return true if the data was successfully removed, false if it doesn't exist
  23797. */
  23798. Scene.prototype.removeExternalData = function (key) {
  23799. return this._externalData.remove(key);
  23800. };
  23801. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23802. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23803. if (mesh.showSubMeshesBoundingBox) {
  23804. var boundingInfo = subMesh.getBoundingInfo();
  23805. if (boundingInfo !== null && boundingInfo !== undefined) {
  23806. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23807. }
  23808. }
  23809. var material = subMesh.getMaterial();
  23810. if (material !== null && material !== undefined) {
  23811. // Render targets
  23812. if (material.getRenderTargetTextures !== undefined) {
  23813. if (this._processedMaterials.indexOf(material) === -1) {
  23814. this._processedMaterials.push(material);
  23815. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23816. }
  23817. }
  23818. // Dispatch
  23819. this._activeIndices.addCount(subMesh.indexCount, false);
  23820. this._renderingManager.dispatch(subMesh, mesh, material);
  23821. }
  23822. }
  23823. };
  23824. Scene.prototype._isInIntermediateRendering = function () {
  23825. return this._intermediateRendering;
  23826. };
  23827. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23828. this._activeMeshCandidateProvider = provider;
  23829. };
  23830. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23831. return this._activeMeshCandidateProvider;
  23832. };
  23833. /**
  23834. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23835. */
  23836. Scene.prototype.freezeActiveMeshes = function () {
  23837. this._evaluateActiveMeshes();
  23838. this._activeMeshesFrozen = true;
  23839. return this;
  23840. };
  23841. /**
  23842. * Use this function to restart evaluating active meshes on every frame
  23843. */
  23844. Scene.prototype.unfreezeActiveMeshes = function () {
  23845. this._activeMeshesFrozen = false;
  23846. return this;
  23847. };
  23848. Scene.prototype._evaluateActiveMeshes = function () {
  23849. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23850. return;
  23851. }
  23852. if (!this.activeCamera) {
  23853. return;
  23854. }
  23855. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23856. this.activeCamera._activeMeshes.reset();
  23857. this._activeMeshes.reset();
  23858. this._renderingManager.reset();
  23859. this._processedMaterials.reset();
  23860. this._activeParticleSystems.reset();
  23861. this._activeSkeletons.reset();
  23862. this._softwareSkinnedMeshes.reset();
  23863. if (this._boundingBoxRenderer) {
  23864. this._boundingBoxRenderer.reset();
  23865. }
  23866. // Meshes
  23867. var meshes;
  23868. var len;
  23869. var checkIsEnabled = true;
  23870. // Determine mesh candidates
  23871. if (this._activeMeshCandidateProvider !== undefined) {
  23872. // Use _activeMeshCandidateProvider
  23873. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23874. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23875. if (meshes !== undefined) {
  23876. len = meshes.length;
  23877. }
  23878. else {
  23879. len = 0;
  23880. }
  23881. }
  23882. else if (this._selectionOctree !== undefined) {
  23883. // Octree
  23884. var selection = this._selectionOctree.select(this._frustumPlanes);
  23885. meshes = selection.data;
  23886. len = selection.length;
  23887. }
  23888. else {
  23889. // Full scene traversal
  23890. len = this.meshes.length;
  23891. meshes = this.meshes;
  23892. }
  23893. // Check each mesh
  23894. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23895. mesh = meshes[meshIndex];
  23896. if (mesh.isBlocked) {
  23897. continue;
  23898. }
  23899. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23900. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23901. continue;
  23902. }
  23903. mesh.computeWorldMatrix();
  23904. // Intersections
  23905. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23906. this._meshesForIntersections.pushNoDuplicate(mesh);
  23907. }
  23908. // Switch to current LOD
  23909. meshLOD = mesh.getLOD(this.activeCamera);
  23910. if (meshLOD === undefined || meshLOD === null) {
  23911. continue;
  23912. }
  23913. mesh._preActivate();
  23914. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23915. this._activeMeshes.push(mesh);
  23916. this.activeCamera._activeMeshes.push(mesh);
  23917. mesh._activate(this._renderId);
  23918. if (meshLOD !== mesh) {
  23919. meshLOD._activate(this._renderId);
  23920. }
  23921. this._activeMesh(mesh, meshLOD);
  23922. }
  23923. }
  23924. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23925. // Particle systems
  23926. if (this.particlesEnabled) {
  23927. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23928. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23929. var particleSystem = this.particleSystems[particleIndex];
  23930. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23931. continue;
  23932. }
  23933. var emitter = particleSystem.emitter;
  23934. if (!emitter.position || emitter.isEnabled()) {
  23935. this._activeParticleSystems.push(particleSystem);
  23936. particleSystem.animate();
  23937. this._renderingManager.dispatchParticles(particleSystem);
  23938. }
  23939. }
  23940. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23941. }
  23942. };
  23943. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23944. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23945. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23946. mesh.skeleton.prepare();
  23947. }
  23948. if (!mesh.computeBonesUsingShaders) {
  23949. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23950. }
  23951. }
  23952. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23953. var boundingInfo = sourceMesh.getBoundingInfo();
  23954. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23955. }
  23956. if (mesh !== undefined && mesh !== null
  23957. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23958. // Submeshes Octrees
  23959. var len;
  23960. var subMeshes;
  23961. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23962. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23963. len = intersections.length;
  23964. subMeshes = intersections.data;
  23965. }
  23966. else {
  23967. subMeshes = mesh.subMeshes;
  23968. len = subMeshes.length;
  23969. }
  23970. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23971. subMesh = subMeshes[subIndex];
  23972. this._evaluateSubMesh(subMesh, mesh);
  23973. }
  23974. }
  23975. };
  23976. Scene.prototype.updateTransformMatrix = function (force) {
  23977. if (!this.activeCamera) {
  23978. return;
  23979. }
  23980. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23981. };
  23982. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23983. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23984. };
  23985. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23986. if (camera && camera._skipRendering) {
  23987. return;
  23988. }
  23989. var engine = this._engine;
  23990. this.activeCamera = camera;
  23991. if (!this.activeCamera)
  23992. throw new Error("Active camera not set");
  23993. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23994. // Viewport
  23995. engine.setViewport(this.activeCamera.viewport);
  23996. // Camera
  23997. this.resetCachedMaterial();
  23998. this._renderId++;
  23999. this.updateTransformMatrix();
  24000. if (camera._alternateCamera) {
  24001. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24002. this._alternateRendering = true;
  24003. }
  24004. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24005. // Meshes
  24006. this._evaluateActiveMeshes();
  24007. // Software skinning
  24008. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24009. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24010. mesh.applySkeleton(mesh.skeleton);
  24011. }
  24012. // Render targets
  24013. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24014. var needsRestoreFrameBuffer = false;
  24015. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24016. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24017. }
  24018. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24019. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24020. }
  24021. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24022. this._intermediateRendering = true;
  24023. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24024. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24025. var renderTarget = this._renderTargets.data[renderIndex];
  24026. if (renderTarget._shouldRender()) {
  24027. this._renderId++;
  24028. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24029. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24030. }
  24031. }
  24032. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24033. this._intermediateRendering = false;
  24034. this._renderId++;
  24035. needsRestoreFrameBuffer = true; // Restore back buffer
  24036. }
  24037. // Render EffecttLayer Texture
  24038. var stencilState = this._engine.getStencilBuffer();
  24039. var renderEffects = false;
  24040. var needStencil = false;
  24041. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24042. this._intermediateRendering = true;
  24043. for (var i = 0; i < this.effectLayers.length; i++) {
  24044. var effectLayer = this.effectLayers[i];
  24045. if (effectLayer.shouldRender() &&
  24046. (!effectLayer.camera ||
  24047. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24048. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24049. renderEffects = true;
  24050. needStencil = needStencil || effectLayer.needStencil();
  24051. var renderTarget = effectLayer._mainTexture;
  24052. if (renderTarget._shouldRender()) {
  24053. this._renderId++;
  24054. renderTarget.render(false, false);
  24055. needsRestoreFrameBuffer = true;
  24056. }
  24057. }
  24058. }
  24059. this._intermediateRendering = false;
  24060. this._renderId++;
  24061. }
  24062. if (needsRestoreFrameBuffer) {
  24063. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24064. }
  24065. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24066. // Prepare Frame
  24067. this.postProcessManager._prepareFrame();
  24068. // Backgrounds
  24069. var layerIndex;
  24070. var layer;
  24071. if (this.layers.length) {
  24072. engine.setDepthBuffer(false);
  24073. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24074. layer = this.layers[layerIndex];
  24075. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24076. layer.render();
  24077. }
  24078. }
  24079. engine.setDepthBuffer(true);
  24080. }
  24081. // Activate effect Layer stencil
  24082. if (needStencil) {
  24083. this._engine.setStencilBuffer(true);
  24084. }
  24085. // Render
  24086. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24087. this._renderingManager.render(null, null, true, true);
  24088. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24089. // Restore effect Layer stencil
  24090. if (needStencil) {
  24091. this._engine.setStencilBuffer(stencilState);
  24092. }
  24093. // Bounding boxes
  24094. if (this._boundingBoxRenderer) {
  24095. this._boundingBoxRenderer.render();
  24096. }
  24097. // Lens flares
  24098. if (this.lensFlaresEnabled) {
  24099. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24100. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24101. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24102. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24103. lensFlareSystem.render();
  24104. }
  24105. }
  24106. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24107. }
  24108. // Foregrounds
  24109. if (this.layers.length) {
  24110. engine.setDepthBuffer(false);
  24111. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24112. layer = this.layers[layerIndex];
  24113. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24114. layer.render();
  24115. }
  24116. }
  24117. engine.setDepthBuffer(true);
  24118. }
  24119. // Effect Layer
  24120. if (renderEffects) {
  24121. engine.setDepthBuffer(false);
  24122. for (var i = 0; i < this.effectLayers.length; i++) {
  24123. if (this.effectLayers[i].shouldRender()) {
  24124. this.effectLayers[i].render();
  24125. }
  24126. }
  24127. engine.setDepthBuffer(true);
  24128. }
  24129. // Finalize frame
  24130. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24131. // Reset some special arrays
  24132. this._renderTargets.reset();
  24133. this._alternateRendering = false;
  24134. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24135. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24136. };
  24137. Scene.prototype._processSubCameras = function (camera) {
  24138. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24139. this._renderForCamera(camera);
  24140. return;
  24141. }
  24142. // rig cameras
  24143. for (var index = 0; index < camera._rigCameras.length; index++) {
  24144. this._renderForCamera(camera._rigCameras[index], camera);
  24145. }
  24146. this.activeCamera = camera;
  24147. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24148. };
  24149. Scene.prototype._checkIntersections = function () {
  24150. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24151. var sourceMesh = this._meshesForIntersections.data[index];
  24152. if (!sourceMesh.actionManager) {
  24153. continue;
  24154. }
  24155. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24156. var action = sourceMesh.actionManager.actions[actionIndex];
  24157. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24158. var parameters = action.getTriggerParameter();
  24159. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24160. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24161. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24162. if (areIntersecting && currentIntersectionInProgress === -1) {
  24163. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24164. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24165. sourceMesh._intersectionsInProgress.push(otherMesh);
  24166. }
  24167. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24168. sourceMesh._intersectionsInProgress.push(otherMesh);
  24169. }
  24170. }
  24171. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24172. //They intersected, and now they don't.
  24173. //is this trigger an exit trigger? execute an event.
  24174. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24175. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24176. }
  24177. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24178. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24179. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24180. }
  24181. }
  24182. }
  24183. }
  24184. }
  24185. };
  24186. Scene.prototype.render = function () {
  24187. if (this.isDisposed) {
  24188. return;
  24189. }
  24190. this._activeParticles.fetchNewFrame();
  24191. this._totalVertices.fetchNewFrame();
  24192. this._activeIndices.fetchNewFrame();
  24193. this._activeBones.fetchNewFrame();
  24194. this._meshesForIntersections.reset();
  24195. this.resetCachedMaterial();
  24196. this.onBeforeAnimationsObservable.notifyObservers(this);
  24197. // Actions
  24198. if (this.actionManager) {
  24199. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24200. }
  24201. //Simplification Queue
  24202. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24203. this.simplificationQueue.executeNext();
  24204. }
  24205. if (this._engine.isDeterministicLockStep()) {
  24206. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24207. var defaultFPS = (60.0 / 1000.0);
  24208. var defaultFrameTime = 1000 / 60; // frame time in MS
  24209. if (this._physicsEngine) {
  24210. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24211. }
  24212. var stepsTaken = 0;
  24213. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24214. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24215. internalSteps = Math.min(internalSteps, maxSubSteps);
  24216. do {
  24217. this.onBeforeStepObservable.notifyObservers(this);
  24218. // Animations
  24219. this._animationRatio = defaultFrameTime * defaultFPS;
  24220. this._animate();
  24221. this.onAfterAnimationsObservable.notifyObservers(this);
  24222. // Physics
  24223. if (this._physicsEngine) {
  24224. this.onBeforePhysicsObservable.notifyObservers(this);
  24225. this._physicsEngine._step(defaultFrameTime / 1000);
  24226. this.onAfterPhysicsObservable.notifyObservers(this);
  24227. }
  24228. this.onAfterStepObservable.notifyObservers(this);
  24229. this._currentStepId++;
  24230. stepsTaken++;
  24231. deltaTime -= defaultFrameTime;
  24232. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24233. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24234. }
  24235. else {
  24236. // Animations
  24237. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24238. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24239. this._animate();
  24240. this.onAfterAnimationsObservable.notifyObservers(this);
  24241. // Physics
  24242. if (this._physicsEngine) {
  24243. this.onBeforePhysicsObservable.notifyObservers(this);
  24244. this._physicsEngine._step(deltaTime / 1000.0);
  24245. this.onAfterPhysicsObservable.notifyObservers(this);
  24246. }
  24247. }
  24248. // update gamepad manager
  24249. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24250. this._gamepadManager._checkGamepadsStatus();
  24251. }
  24252. // Before render
  24253. this.onBeforeRenderObservable.notifyObservers(this);
  24254. // Update Cameras
  24255. if (this.activeCameras.length > 0) {
  24256. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24257. var camera = this.activeCameras[cameraIndex];
  24258. camera.update();
  24259. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24260. // rig cameras
  24261. for (var index = 0; index < camera._rigCameras.length; index++) {
  24262. camera._rigCameras[index].update();
  24263. }
  24264. }
  24265. }
  24266. }
  24267. else if (this.activeCamera) {
  24268. this.activeCamera.update();
  24269. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24270. // rig cameras
  24271. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24272. this.activeCamera._rigCameras[index].update();
  24273. }
  24274. }
  24275. }
  24276. // Customs render targets
  24277. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24278. var engine = this.getEngine();
  24279. var currentActiveCamera = this.activeCamera;
  24280. if (this.renderTargetsEnabled) {
  24281. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24282. this._intermediateRendering = true;
  24283. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24284. var renderTarget = this.customRenderTargets[customIndex];
  24285. if (renderTarget._shouldRender()) {
  24286. this._renderId++;
  24287. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24288. if (!this.activeCamera)
  24289. throw new Error("Active camera not set");
  24290. // Viewport
  24291. engine.setViewport(this.activeCamera.viewport);
  24292. // Camera
  24293. this.updateTransformMatrix();
  24294. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24295. }
  24296. }
  24297. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24298. this._intermediateRendering = false;
  24299. this._renderId++;
  24300. }
  24301. // Restore back buffer
  24302. if (this.customRenderTargets.length > 0) {
  24303. engine.restoreDefaultFramebuffer();
  24304. }
  24305. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24306. this.activeCamera = currentActiveCamera;
  24307. // Procedural textures
  24308. if (this.proceduralTexturesEnabled) {
  24309. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24310. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24311. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24312. if (proceduralTexture._shouldRender()) {
  24313. proceduralTexture.render();
  24314. }
  24315. }
  24316. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24317. }
  24318. // Clear
  24319. if (this.autoClearDepthAndStencil || this.autoClear) {
  24320. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24321. }
  24322. // Shadows
  24323. if (this.shadowsEnabled) {
  24324. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24325. var light = this.lights[lightIndex];
  24326. var shadowGenerator = light.getShadowGenerator();
  24327. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24328. var shadowMap = (shadowGenerator.getShadowMap());
  24329. if (this.textures.indexOf(shadowMap) !== -1) {
  24330. this._renderTargets.push(shadowMap);
  24331. }
  24332. }
  24333. }
  24334. }
  24335. // Depth renderer
  24336. for (var key in this._depthRenderer) {
  24337. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24338. }
  24339. // Geometry renderer
  24340. if (this._geometryBufferRenderer) {
  24341. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24342. }
  24343. // RenderPipeline
  24344. if (this._postProcessRenderPipelineManager) {
  24345. this._postProcessRenderPipelineManager.update();
  24346. }
  24347. // Multi-cameras?
  24348. if (this.activeCameras.length > 0) {
  24349. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24350. if (cameraIndex > 0) {
  24351. this._engine.clear(null, false, true, true);
  24352. }
  24353. this._processSubCameras(this.activeCameras[cameraIndex]);
  24354. }
  24355. }
  24356. else {
  24357. if (!this.activeCamera) {
  24358. throw new Error("No camera defined");
  24359. }
  24360. this._processSubCameras(this.activeCamera);
  24361. }
  24362. // Intersection checks
  24363. this._checkIntersections();
  24364. // Update the audio listener attached to the camera
  24365. if (BABYLON.AudioEngine) {
  24366. this._updateAudioParameters();
  24367. }
  24368. // After render
  24369. if (this.afterRender) {
  24370. this.afterRender();
  24371. }
  24372. this.onAfterRenderObservable.notifyObservers(this);
  24373. // Cleaning
  24374. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24375. var data = this._toBeDisposed.data[index];
  24376. if (data) {
  24377. data.dispose();
  24378. }
  24379. this._toBeDisposed[index] = null;
  24380. }
  24381. this._toBeDisposed.reset();
  24382. if (this.dumpNextRenderTargets) {
  24383. this.dumpNextRenderTargets = false;
  24384. }
  24385. this._activeBones.addCount(0, true);
  24386. this._activeIndices.addCount(0, true);
  24387. this._activeParticles.addCount(0, true);
  24388. };
  24389. Scene.prototype._updateAudioParameters = function () {
  24390. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24391. return;
  24392. }
  24393. var listeningCamera;
  24394. var audioEngine = BABYLON.Engine.audioEngine;
  24395. if (this.activeCameras.length > 0) {
  24396. listeningCamera = this.activeCameras[0];
  24397. }
  24398. else {
  24399. listeningCamera = this.activeCamera;
  24400. }
  24401. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24402. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24403. // for VR cameras
  24404. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24405. listeningCamera = listeningCamera.rigCameras[0];
  24406. }
  24407. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24408. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24409. cameraDirection.normalize();
  24410. // To avoid some errors on GearVR
  24411. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24412. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24413. }
  24414. var i;
  24415. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24416. var sound = this.mainSoundTrack.soundCollection[i];
  24417. if (sound.useCustomAttenuation) {
  24418. sound.updateDistanceFromListener();
  24419. }
  24420. }
  24421. for (i = 0; i < this.soundTracks.length; i++) {
  24422. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24423. sound = this.soundTracks[i].soundCollection[j];
  24424. if (sound.useCustomAttenuation) {
  24425. sound.updateDistanceFromListener();
  24426. }
  24427. }
  24428. }
  24429. }
  24430. };
  24431. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24432. // Audio
  24433. get: function () {
  24434. return this._audioEnabled;
  24435. },
  24436. set: function (value) {
  24437. this._audioEnabled = value;
  24438. if (BABYLON.AudioEngine) {
  24439. if (this._audioEnabled) {
  24440. this._enableAudio();
  24441. }
  24442. else {
  24443. this._disableAudio();
  24444. }
  24445. }
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Scene.prototype._disableAudio = function () {
  24451. var i;
  24452. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24453. this.mainSoundTrack.soundCollection[i].pause();
  24454. }
  24455. for (i = 0; i < this.soundTracks.length; i++) {
  24456. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24457. this.soundTracks[i].soundCollection[j].pause();
  24458. }
  24459. }
  24460. };
  24461. Scene.prototype._enableAudio = function () {
  24462. var i;
  24463. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24464. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24465. this.mainSoundTrack.soundCollection[i].play();
  24466. }
  24467. }
  24468. for (i = 0; i < this.soundTracks.length; i++) {
  24469. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24470. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24471. this.soundTracks[i].soundCollection[j].play();
  24472. }
  24473. }
  24474. }
  24475. };
  24476. Object.defineProperty(Scene.prototype, "headphone", {
  24477. get: function () {
  24478. return this._headphone;
  24479. },
  24480. set: function (value) {
  24481. this._headphone = value;
  24482. if (BABYLON.AudioEngine) {
  24483. if (this._headphone) {
  24484. this._switchAudioModeForHeadphones();
  24485. }
  24486. else {
  24487. this._switchAudioModeForNormalSpeakers();
  24488. }
  24489. }
  24490. },
  24491. enumerable: true,
  24492. configurable: true
  24493. });
  24494. Scene.prototype._switchAudioModeForHeadphones = function () {
  24495. this.mainSoundTrack.switchPanningModelToHRTF();
  24496. for (var i = 0; i < this.soundTracks.length; i++) {
  24497. this.soundTracks[i].switchPanningModelToHRTF();
  24498. }
  24499. };
  24500. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24501. this.mainSoundTrack.switchPanningModelToEqualPower();
  24502. for (var i = 0; i < this.soundTracks.length; i++) {
  24503. this.soundTracks[i].switchPanningModelToEqualPower();
  24504. }
  24505. };
  24506. /**
  24507. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24508. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24509. * @returns the created depth renderer
  24510. */
  24511. Scene.prototype.enableDepthRenderer = function (camera) {
  24512. camera = camera || this.activeCamera;
  24513. if (!camera) {
  24514. throw "No camera available to enable depth renderer";
  24515. }
  24516. if (!this._depthRenderer[camera.id]) {
  24517. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24518. }
  24519. return this._depthRenderer[camera.id];
  24520. };
  24521. /**
  24522. * Disables a depth renderer for a given camera
  24523. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24524. */
  24525. Scene.prototype.disableDepthRenderer = function (camera) {
  24526. camera = camera || this.activeCamera;
  24527. if (!camera || !this._depthRenderer[camera.id]) {
  24528. return;
  24529. }
  24530. this._depthRenderer[camera.id].dispose();
  24531. delete this._depthRenderer[camera.id];
  24532. };
  24533. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24534. if (ratio === void 0) { ratio = 1; }
  24535. if (this._geometryBufferRenderer) {
  24536. return this._geometryBufferRenderer;
  24537. }
  24538. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24539. if (!this._geometryBufferRenderer.isSupported) {
  24540. this._geometryBufferRenderer = null;
  24541. }
  24542. return this._geometryBufferRenderer;
  24543. };
  24544. Scene.prototype.disableGeometryBufferRenderer = function () {
  24545. if (!this._geometryBufferRenderer) {
  24546. return;
  24547. }
  24548. this._geometryBufferRenderer.dispose();
  24549. this._geometryBufferRenderer = null;
  24550. };
  24551. Scene.prototype.freezeMaterials = function () {
  24552. for (var i = 0; i < this.materials.length; i++) {
  24553. this.materials[i].freeze();
  24554. }
  24555. };
  24556. Scene.prototype.unfreezeMaterials = function () {
  24557. for (var i = 0; i < this.materials.length; i++) {
  24558. this.materials[i].unfreeze();
  24559. }
  24560. };
  24561. Scene.prototype.dispose = function () {
  24562. this.beforeRender = null;
  24563. this.afterRender = null;
  24564. this.skeletons = [];
  24565. this.morphTargetManagers = [];
  24566. this.importedMeshesFiles = new Array();
  24567. this.stopAllAnimations();
  24568. this.resetCachedMaterial();
  24569. for (var key in this._depthRenderer) {
  24570. this._depthRenderer[key].dispose();
  24571. }
  24572. if (this._gamepadManager) {
  24573. this._gamepadManager.dispose();
  24574. this._gamepadManager = null;
  24575. }
  24576. // Smart arrays
  24577. if (this.activeCamera) {
  24578. this.activeCamera._activeMeshes.dispose();
  24579. this.activeCamera = null;
  24580. }
  24581. this._activeMeshes.dispose();
  24582. this._renderingManager.dispose();
  24583. this._processedMaterials.dispose();
  24584. this._activeParticleSystems.dispose();
  24585. this._activeSkeletons.dispose();
  24586. this._softwareSkinnedMeshes.dispose();
  24587. this._renderTargets.dispose();
  24588. if (this._boundingBoxRenderer) {
  24589. this._boundingBoxRenderer.dispose();
  24590. }
  24591. this._meshesForIntersections.dispose();
  24592. this._toBeDisposed.dispose();
  24593. // Abort active requests
  24594. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24595. var request = _a[_i];
  24596. request.abort();
  24597. }
  24598. // Debug layer
  24599. if (this._debugLayer) {
  24600. this._debugLayer.hide();
  24601. }
  24602. // Events
  24603. this.onDisposeObservable.notifyObservers(this);
  24604. this.onDisposeObservable.clear();
  24605. this.onBeforeRenderObservable.clear();
  24606. this.onAfterRenderObservable.clear();
  24607. this.OnBeforeRenderTargetsRenderObservable.clear();
  24608. this.OnAfterRenderTargetsRenderObservable.clear();
  24609. this.onAfterStepObservable.clear();
  24610. this.onBeforeStepObservable.clear();
  24611. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24612. this.onAfterActiveMeshesEvaluationObservable.clear();
  24613. this.onBeforeParticlesRenderingObservable.clear();
  24614. this.onAfterParticlesRenderingObservable.clear();
  24615. this.onBeforeSpritesRenderingObservable.clear();
  24616. this.onAfterSpritesRenderingObservable.clear();
  24617. this.onBeforeDrawPhaseObservable.clear();
  24618. this.onAfterDrawPhaseObservable.clear();
  24619. this.onBeforePhysicsObservable.clear();
  24620. this.onAfterPhysicsObservable.clear();
  24621. this.onBeforeAnimationsObservable.clear();
  24622. this.onAfterAnimationsObservable.clear();
  24623. this.onDataLoadedObservable.clear();
  24624. this.detachControl();
  24625. // Release sounds & sounds tracks
  24626. if (BABYLON.AudioEngine) {
  24627. this.disposeSounds();
  24628. }
  24629. // VR Helper
  24630. if (this.VRHelper) {
  24631. this.VRHelper.dispose();
  24632. }
  24633. // Detach cameras
  24634. var canvas = this._engine.getRenderingCanvas();
  24635. if (canvas) {
  24636. var index;
  24637. for (index = 0; index < this.cameras.length; index++) {
  24638. this.cameras[index].detachControl(canvas);
  24639. }
  24640. }
  24641. // Release animation groups
  24642. while (this.animationGroups.length) {
  24643. this.animationGroups[0].dispose();
  24644. }
  24645. // Release lights
  24646. while (this.lights.length) {
  24647. this.lights[0].dispose();
  24648. }
  24649. // Release meshes
  24650. while (this.meshes.length) {
  24651. this.meshes[0].dispose(true);
  24652. }
  24653. while (this.transformNodes.length) {
  24654. this.removeTransformNode(this.transformNodes[0]);
  24655. }
  24656. // Release cameras
  24657. while (this.cameras.length) {
  24658. this.cameras[0].dispose();
  24659. }
  24660. // Release materials
  24661. if (this.defaultMaterial) {
  24662. this.defaultMaterial.dispose();
  24663. }
  24664. while (this.multiMaterials.length) {
  24665. this.multiMaterials[0].dispose();
  24666. }
  24667. while (this.materials.length) {
  24668. this.materials[0].dispose();
  24669. }
  24670. // Release particles
  24671. while (this.particleSystems.length) {
  24672. this.particleSystems[0].dispose();
  24673. }
  24674. // Release sprites
  24675. while (this.spriteManagers.length) {
  24676. this.spriteManagers[0].dispose();
  24677. }
  24678. // Release postProcesses
  24679. while (this.postProcesses.length) {
  24680. this.postProcesses[0].dispose();
  24681. }
  24682. // Release layers
  24683. while (this.layers.length) {
  24684. this.layers[0].dispose();
  24685. }
  24686. while (this.effectLayers.length) {
  24687. this.effectLayers[0].dispose();
  24688. }
  24689. // Release textures
  24690. while (this.textures.length) {
  24691. this.textures[0].dispose();
  24692. }
  24693. // Release UBO
  24694. this._sceneUbo.dispose();
  24695. if (this._alternateSceneUbo) {
  24696. this._alternateSceneUbo.dispose();
  24697. }
  24698. // Post-processes
  24699. this.postProcessManager.dispose();
  24700. if (this._postProcessRenderPipelineManager) {
  24701. this._postProcessRenderPipelineManager.dispose();
  24702. }
  24703. // Physics
  24704. if (this._physicsEngine) {
  24705. this.disablePhysicsEngine();
  24706. }
  24707. // Remove from engine
  24708. index = this._engine.scenes.indexOf(this);
  24709. if (index > -1) {
  24710. this._engine.scenes.splice(index, 1);
  24711. }
  24712. this._engine.wipeCaches(true);
  24713. this._isDisposed = true;
  24714. };
  24715. Object.defineProperty(Scene.prototype, "isDisposed", {
  24716. get: function () {
  24717. return this._isDisposed;
  24718. },
  24719. enumerable: true,
  24720. configurable: true
  24721. });
  24722. // Release sounds & sounds tracks
  24723. Scene.prototype.disposeSounds = function () {
  24724. if (!this._mainSoundTrack) {
  24725. return;
  24726. }
  24727. this.mainSoundTrack.dispose();
  24728. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24729. this.soundTracks[scIndex].dispose();
  24730. }
  24731. };
  24732. // Octrees
  24733. /**
  24734. * Get the world extend vectors with an optional filter
  24735. *
  24736. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24737. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24738. */
  24739. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24740. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24741. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24742. filterPredicate = filterPredicate || (function () { return true; });
  24743. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24744. mesh.computeWorldMatrix(true);
  24745. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24746. return;
  24747. }
  24748. var boundingInfo = mesh.getBoundingInfo();
  24749. var minBox = boundingInfo.boundingBox.minimumWorld;
  24750. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24751. BABYLON.Tools.CheckExtends(minBox, min, max);
  24752. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24753. });
  24754. return {
  24755. min: min,
  24756. max: max
  24757. };
  24758. };
  24759. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24760. if (maxCapacity === void 0) { maxCapacity = 64; }
  24761. if (maxDepth === void 0) { maxDepth = 2; }
  24762. if (!this._selectionOctree) {
  24763. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24764. }
  24765. var worldExtends = this.getWorldExtends();
  24766. // Update octree
  24767. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24768. return this._selectionOctree;
  24769. };
  24770. // Picking
  24771. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24772. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24773. var result = BABYLON.Ray.Zero();
  24774. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24775. return result;
  24776. };
  24777. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24778. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24779. var engine = this._engine;
  24780. if (!camera) {
  24781. if (!this.activeCamera)
  24782. throw new Error("Active camera not set");
  24783. camera = this.activeCamera;
  24784. }
  24785. var cameraViewport = camera.viewport;
  24786. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24787. // Moving coordinates to local viewport world
  24788. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24789. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24790. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24791. return this;
  24792. };
  24793. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24794. var result = BABYLON.Ray.Zero();
  24795. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24796. return result;
  24797. };
  24798. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24799. if (!BABYLON.PickingInfo) {
  24800. return this;
  24801. }
  24802. var engine = this._engine;
  24803. if (!camera) {
  24804. if (!this.activeCamera)
  24805. throw new Error("Active camera not set");
  24806. camera = this.activeCamera;
  24807. }
  24808. var cameraViewport = camera.viewport;
  24809. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24810. var identity = BABYLON.Matrix.Identity();
  24811. // Moving coordinates to local viewport world
  24812. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24813. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24814. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24815. return this;
  24816. };
  24817. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24818. if (!BABYLON.PickingInfo) {
  24819. return null;
  24820. }
  24821. var pickingInfo = null;
  24822. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24823. var mesh = this.meshes[meshIndex];
  24824. if (predicate) {
  24825. if (!predicate(mesh)) {
  24826. continue;
  24827. }
  24828. }
  24829. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24830. continue;
  24831. }
  24832. var world = mesh.getWorldMatrix();
  24833. var ray = rayFunction(world);
  24834. var result = mesh.intersects(ray, fastCheck);
  24835. if (!result || !result.hit)
  24836. continue;
  24837. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24838. continue;
  24839. pickingInfo = result;
  24840. if (fastCheck) {
  24841. break;
  24842. }
  24843. }
  24844. return pickingInfo || new BABYLON.PickingInfo();
  24845. };
  24846. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24847. if (!BABYLON.PickingInfo) {
  24848. return null;
  24849. }
  24850. var pickingInfos = new Array();
  24851. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24852. var mesh = this.meshes[meshIndex];
  24853. if (predicate) {
  24854. if (!predicate(mesh)) {
  24855. continue;
  24856. }
  24857. }
  24858. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24859. continue;
  24860. }
  24861. var world = mesh.getWorldMatrix();
  24862. var ray = rayFunction(world);
  24863. var result = mesh.intersects(ray, false);
  24864. if (!result || !result.hit)
  24865. continue;
  24866. pickingInfos.push(result);
  24867. }
  24868. return pickingInfos;
  24869. };
  24870. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24871. if (!BABYLON.PickingInfo) {
  24872. return null;
  24873. }
  24874. var pickingInfo = null;
  24875. if (!camera) {
  24876. if (!this.activeCamera) {
  24877. return null;
  24878. }
  24879. camera = this.activeCamera;
  24880. }
  24881. if (this.spriteManagers.length > 0) {
  24882. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24883. var spriteManager = this.spriteManagers[spriteIndex];
  24884. if (!spriteManager.isPickable) {
  24885. continue;
  24886. }
  24887. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24888. if (!result || !result.hit)
  24889. continue;
  24890. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24891. continue;
  24892. pickingInfo = result;
  24893. if (fastCheck) {
  24894. break;
  24895. }
  24896. }
  24897. }
  24898. return pickingInfo || new BABYLON.PickingInfo();
  24899. };
  24900. /** Launch a ray to try to pick a mesh in the scene
  24901. * @param x position on screen
  24902. * @param y position on screen
  24903. * @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
  24904. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24905. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24906. */
  24907. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24908. var _this = this;
  24909. if (!BABYLON.PickingInfo) {
  24910. return null;
  24911. }
  24912. return this._internalPick(function (world) {
  24913. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24914. return _this._tempPickingRay;
  24915. }, predicate, fastCheck);
  24916. };
  24917. /** Launch a ray to try to pick a sprite in the scene
  24918. * @param x position on screen
  24919. * @param y position on screen
  24920. * @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
  24921. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24922. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24923. */
  24924. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24925. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24926. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24927. };
  24928. /** Use the given ray to pick a mesh in the scene
  24929. * @param ray The ray to use to pick meshes
  24930. * @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
  24931. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24932. */
  24933. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24934. var _this = this;
  24935. return this._internalPick(function (world) {
  24936. if (!_this._pickWithRayInverseMatrix) {
  24937. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24938. }
  24939. world.invertToRef(_this._pickWithRayInverseMatrix);
  24940. if (!_this._cachedRayForTransform) {
  24941. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24942. }
  24943. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24944. return _this._cachedRayForTransform;
  24945. }, predicate, fastCheck);
  24946. };
  24947. /**
  24948. * Launch a ray to try to pick a mesh in the scene
  24949. * @param x X position on screen
  24950. * @param y Y position on screen
  24951. * @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
  24952. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24953. */
  24954. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24955. var _this = this;
  24956. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24957. };
  24958. /**
  24959. * Launch a ray to try to pick a mesh in the scene
  24960. * @param ray Ray to use
  24961. * @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
  24962. */
  24963. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24964. var _this = this;
  24965. return this._internalMultiPick(function (world) {
  24966. if (!_this._pickWithRayInverseMatrix) {
  24967. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24968. }
  24969. world.invertToRef(_this._pickWithRayInverseMatrix);
  24970. if (!_this._cachedRayForTransform) {
  24971. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24972. }
  24973. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24974. return _this._cachedRayForTransform;
  24975. }, predicate);
  24976. };
  24977. Scene.prototype.setPointerOverMesh = function (mesh) {
  24978. if (this._pointerOverMesh === mesh) {
  24979. return;
  24980. }
  24981. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24982. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24983. }
  24984. this._pointerOverMesh = mesh;
  24985. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24986. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24987. }
  24988. };
  24989. Scene.prototype.getPointerOverMesh = function () {
  24990. return this._pointerOverMesh;
  24991. };
  24992. Scene.prototype.setPointerOverSprite = function (sprite) {
  24993. if (this._pointerOverSprite === sprite) {
  24994. return;
  24995. }
  24996. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24997. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24998. }
  24999. this._pointerOverSprite = sprite;
  25000. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25001. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25002. }
  25003. };
  25004. Scene.prototype.getPointerOverSprite = function () {
  25005. return this._pointerOverSprite;
  25006. };
  25007. // Physics
  25008. Scene.prototype.getPhysicsEngine = function () {
  25009. return this._physicsEngine;
  25010. };
  25011. /**
  25012. * Enables physics to the current scene
  25013. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25014. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25015. * @return {boolean} was the physics engine initialized
  25016. */
  25017. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25018. if (gravity === void 0) { gravity = null; }
  25019. if (this._physicsEngine) {
  25020. return true;
  25021. }
  25022. try {
  25023. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25024. return true;
  25025. }
  25026. catch (e) {
  25027. BABYLON.Tools.Error(e.message);
  25028. return false;
  25029. }
  25030. };
  25031. Scene.prototype.disablePhysicsEngine = function () {
  25032. if (!this._physicsEngine) {
  25033. return;
  25034. }
  25035. this._physicsEngine.dispose();
  25036. this._physicsEngine = null;
  25037. };
  25038. Scene.prototype.isPhysicsEnabled = function () {
  25039. return this._physicsEngine !== undefined;
  25040. };
  25041. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25042. var mesh = compound.parts[0].mesh;
  25043. if (mesh.physicsImpostor) {
  25044. mesh.physicsImpostor.dispose();
  25045. mesh.physicsImpostor = null;
  25046. }
  25047. };
  25048. // Misc.
  25049. Scene.prototype._rebuildGeometries = function () {
  25050. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25051. var geometry = _a[_i];
  25052. geometry._rebuild();
  25053. }
  25054. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25055. var mesh = _c[_b];
  25056. mesh._rebuild();
  25057. }
  25058. if (this.postProcessManager) {
  25059. this.postProcessManager._rebuild();
  25060. }
  25061. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25062. var layer = _e[_d];
  25063. layer._rebuild();
  25064. }
  25065. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25066. var effectLayer = _g[_f];
  25067. effectLayer._rebuild();
  25068. }
  25069. if (this._boundingBoxRenderer) {
  25070. this._boundingBoxRenderer._rebuild();
  25071. }
  25072. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25073. var system = _j[_h];
  25074. system.rebuild();
  25075. }
  25076. if (this._postProcessRenderPipelineManager) {
  25077. this._postProcessRenderPipelineManager._rebuild();
  25078. }
  25079. };
  25080. Scene.prototype._rebuildTextures = function () {
  25081. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25082. var texture = _a[_i];
  25083. texture._rebuild();
  25084. }
  25085. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25086. };
  25087. /**
  25088. * Creates a default light for the scene.
  25089. * @param replace Whether to replace the existing lights in the scene.
  25090. */
  25091. Scene.prototype.createDefaultLight = function (replace) {
  25092. if (replace === void 0) { replace = false; }
  25093. // Dispose existing light in replace mode.
  25094. if (replace) {
  25095. if (this.lights) {
  25096. for (var i = 0; i < this.lights.length; i++) {
  25097. this.lights[i].dispose();
  25098. }
  25099. }
  25100. }
  25101. // Light
  25102. if (this.lights.length === 0) {
  25103. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25104. }
  25105. };
  25106. /**
  25107. * Creates a default camera for the scene.
  25108. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25109. * @param replace Whether to replace the existing active camera in the scene.
  25110. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25111. */
  25112. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25113. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25114. if (replace === void 0) { replace = false; }
  25115. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25116. // Dispose existing camera in replace mode.
  25117. if (replace) {
  25118. if (this.activeCamera) {
  25119. this.activeCamera.dispose();
  25120. this.activeCamera = null;
  25121. }
  25122. }
  25123. // Camera
  25124. if (!this.activeCamera) {
  25125. var worldExtends = this.getWorldExtends();
  25126. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25127. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25128. var camera;
  25129. var radius = worldSize.length() * 1.5;
  25130. // empty scene scenario!
  25131. if (!isFinite(radius)) {
  25132. radius = 1;
  25133. worldCenter.copyFromFloats(0, 0, 0);
  25134. }
  25135. if (createArcRotateCamera) {
  25136. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25137. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25138. arcRotateCamera.wheelPrecision = 100 / radius;
  25139. camera = arcRotateCamera;
  25140. }
  25141. else {
  25142. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25143. freeCamera.setTarget(worldCenter);
  25144. camera = freeCamera;
  25145. }
  25146. camera.minZ = radius * 0.01;
  25147. camera.maxZ = radius * 1000;
  25148. camera.speed = radius * 0.2;
  25149. this.activeCamera = camera;
  25150. var canvas = this.getEngine().getRenderingCanvas();
  25151. if (attachCameraControls && canvas) {
  25152. camera.attachControl(canvas);
  25153. }
  25154. }
  25155. };
  25156. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25157. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25158. if (replace === void 0) { replace = false; }
  25159. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25160. this.createDefaultLight(replace);
  25161. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25162. };
  25163. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25164. if (pbr === void 0) { pbr = false; }
  25165. if (scale === void 0) { scale = 1000; }
  25166. if (blur === void 0) { blur = 0; }
  25167. if (environmentTexture) {
  25168. this.environmentTexture = environmentTexture;
  25169. }
  25170. if (!this.environmentTexture) {
  25171. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25172. return null;
  25173. }
  25174. // Skybox
  25175. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25176. if (pbr) {
  25177. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25178. hdrSkyboxMaterial.backFaceCulling = false;
  25179. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25180. if (hdrSkyboxMaterial.reflectionTexture) {
  25181. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25182. }
  25183. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25184. hdrSkyboxMaterial.disableLighting = true;
  25185. hdrSkyboxMaterial.twoSidedLighting = true;
  25186. hdrSkybox.infiniteDistance = true;
  25187. hdrSkybox.material = hdrSkyboxMaterial;
  25188. }
  25189. else {
  25190. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25191. skyboxMaterial.backFaceCulling = false;
  25192. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25193. if (skyboxMaterial.reflectionTexture) {
  25194. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25195. }
  25196. skyboxMaterial.disableLighting = true;
  25197. hdrSkybox.infiniteDistance = true;
  25198. hdrSkybox.material = skyboxMaterial;
  25199. }
  25200. return hdrSkybox;
  25201. };
  25202. Scene.prototype.createDefaultEnvironment = function (options) {
  25203. if (BABYLON.EnvironmentHelper) {
  25204. return new BABYLON.EnvironmentHelper(options, this);
  25205. }
  25206. return null;
  25207. };
  25208. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25209. if (webVROptions === void 0) { webVROptions = {}; }
  25210. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25211. };
  25212. // Tags
  25213. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25214. if (tagsQuery === undefined) {
  25215. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25216. return list;
  25217. }
  25218. var listByTags = [];
  25219. forEach = forEach || (function (item) { return; });
  25220. for (var i in list) {
  25221. var item = list[i];
  25222. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25223. listByTags.push(item);
  25224. forEach(item);
  25225. }
  25226. }
  25227. return listByTags;
  25228. };
  25229. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25230. return this._getByTags(this.meshes, tagsQuery, forEach);
  25231. };
  25232. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25233. return this._getByTags(this.cameras, tagsQuery, forEach);
  25234. };
  25235. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25236. return this._getByTags(this.lights, tagsQuery, forEach);
  25237. };
  25238. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25239. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25240. };
  25241. /**
  25242. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25243. * This allowed control for front to back rendering or reversly depending of the special needs.
  25244. *
  25245. * @param renderingGroupId The rendering group id corresponding to its index
  25246. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25247. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25248. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25249. */
  25250. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25251. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25252. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25253. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25254. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25255. };
  25256. /**
  25257. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25258. *
  25259. * @param renderingGroupId The rendering group id corresponding to its index
  25260. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25261. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25262. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25263. */
  25264. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25265. if (depth === void 0) { depth = true; }
  25266. if (stencil === void 0) { stencil = true; }
  25267. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25268. };
  25269. /**
  25270. * Will flag all materials as dirty to trigger new shader compilation
  25271. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25272. */
  25273. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25274. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25275. var material = _a[_i];
  25276. if (predicate && !predicate(material)) {
  25277. continue;
  25278. }
  25279. material.markAsDirty(flag);
  25280. }
  25281. };
  25282. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25283. var _this = this;
  25284. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25285. this._activeRequests.push(request);
  25286. request.onCompleteObservable.add(function (request) {
  25287. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25288. });
  25289. return request;
  25290. };
  25291. /** @ignore */
  25292. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25293. var _this = this;
  25294. return new Promise(function (resolve, reject) {
  25295. _this._loadFile(url, function (data) {
  25296. resolve(data);
  25297. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25298. reject(exception);
  25299. });
  25300. });
  25301. };
  25302. // Statics
  25303. Scene._FOGMODE_NONE = 0;
  25304. Scene._FOGMODE_EXP = 1;
  25305. Scene._FOGMODE_EXP2 = 2;
  25306. Scene._FOGMODE_LINEAR = 3;
  25307. Scene._uniqueIdCounter = 0;
  25308. Scene.MinDeltaTime = 1.0;
  25309. Scene.MaxDeltaTime = 1000.0;
  25310. /** The distance in pixel that you have to move to prevent some events */
  25311. Scene.DragMovementThreshold = 10; // in pixels
  25312. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25313. Scene.LongPressDelay = 500; // in milliseconds
  25314. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25315. Scene.DoubleClickDelay = 300; // in milliseconds
  25316. /** If you need to check double click without raising a single click at first click, enable this flag */
  25317. Scene.ExclusiveDoubleClickMode = false;
  25318. return Scene;
  25319. }());
  25320. BABYLON.Scene = Scene;
  25321. })(BABYLON || (BABYLON = {}));
  25322. //# sourceMappingURL=babylon.scene.js.map
  25323. var BABYLON;
  25324. (function (BABYLON) {
  25325. /**
  25326. * Set of assets to keep when moving a scene into an asset container.
  25327. */
  25328. var KeepAssets = /** @class */ (function () {
  25329. function KeepAssets() {
  25330. /**
  25331. * Cameras to keep.
  25332. */
  25333. this.cameras = new Array();
  25334. /**
  25335. * Lights to keep.
  25336. */
  25337. this.lights = new Array();
  25338. /**
  25339. * Meshes to keep.
  25340. */
  25341. this.meshes = new Array();
  25342. /**
  25343. * Skeletons to keep.
  25344. */
  25345. this.skeletons = new Array();
  25346. /**
  25347. * ParticleSystems to keep.
  25348. */
  25349. this.particleSystems = new Array();
  25350. /**
  25351. * Animations to keep.
  25352. */
  25353. this.animations = new Array();
  25354. /**
  25355. * MultiMaterials to keep.
  25356. */
  25357. this.multiMaterials = new Array();
  25358. /**
  25359. * Materials to keep.
  25360. */
  25361. this.materials = new Array();
  25362. /**
  25363. * MorphTargetManagers to keep.
  25364. */
  25365. this.morphTargetManagers = new Array();
  25366. /**
  25367. * Geometries to keep.
  25368. */
  25369. this.geometries = new Array();
  25370. /**
  25371. * TransformNodes to keep.
  25372. */
  25373. this.transformNodes = new Array();
  25374. /**
  25375. * LensFlareSystems to keep.
  25376. */
  25377. this.lensFlareSystems = new Array();
  25378. /**
  25379. * ShadowGenerators to keep.
  25380. */
  25381. this.shadowGenerators = new Array();
  25382. /**
  25383. * ActionManagers to keep.
  25384. */
  25385. this.actionManagers = new Array();
  25386. /**
  25387. * Sounds to keep.
  25388. */
  25389. this.sounds = new Array();
  25390. }
  25391. return KeepAssets;
  25392. }());
  25393. BABYLON.KeepAssets = KeepAssets;
  25394. /**
  25395. * Container with a set of assets that can be added or removed from a scene.
  25396. */
  25397. var AssetContainer = /** @class */ (function () {
  25398. /**
  25399. * Instantiates an AssetContainer.
  25400. * @param scene The scene the AssetContainer belongs to.
  25401. */
  25402. function AssetContainer(scene) {
  25403. // Objects
  25404. /**
  25405. * Cameras populated in the container.
  25406. */
  25407. this.cameras = new Array();
  25408. /**
  25409. * Lights populated in the container.
  25410. */
  25411. this.lights = new Array();
  25412. /**
  25413. * Meshes populated in the container.
  25414. */
  25415. this.meshes = new Array();
  25416. /**
  25417. * Skeletons populated in the container.
  25418. */
  25419. this.skeletons = new Array();
  25420. /**
  25421. * ParticleSystems populated in the container.
  25422. */
  25423. this.particleSystems = new Array();
  25424. /**
  25425. * Animations populated in the container.
  25426. */
  25427. this.animations = new Array();
  25428. /**
  25429. * MultiMaterials populated in the container.
  25430. */
  25431. this.multiMaterials = new Array();
  25432. /**
  25433. * Materials populated in the container.
  25434. */
  25435. this.materials = new Array();
  25436. /**
  25437. * MorphTargetManagers populated in the container.
  25438. */
  25439. this.morphTargetManagers = new Array();
  25440. /**
  25441. * Geometries populated in the container.
  25442. */
  25443. this.geometries = new Array();
  25444. /**
  25445. * TransformNodes populated in the container.
  25446. */
  25447. this.transformNodes = new Array();
  25448. /**
  25449. * LensFlareSystems populated in the container.
  25450. */
  25451. this.lensFlareSystems = new Array();
  25452. /**
  25453. * ShadowGenerators populated in the container.
  25454. */
  25455. this.shadowGenerators = new Array();
  25456. /**
  25457. * ActionManagers populated in the container.
  25458. */
  25459. this.actionManagers = new Array();
  25460. /**
  25461. * Sounds populated in the container.
  25462. */
  25463. this.sounds = new Array();
  25464. this.scene = scene;
  25465. }
  25466. /**
  25467. * Adds all the assets from the container to the scene.
  25468. */
  25469. AssetContainer.prototype.addAllToScene = function () {
  25470. var _this = this;
  25471. this.cameras.forEach(function (o) {
  25472. _this.scene.addCamera(o);
  25473. });
  25474. this.lights.forEach(function (o) {
  25475. _this.scene.addLight(o);
  25476. });
  25477. this.meshes.forEach(function (o) {
  25478. _this.scene.addMesh(o);
  25479. });
  25480. this.skeletons.forEach(function (o) {
  25481. _this.scene.addSkeleton(o);
  25482. });
  25483. this.particleSystems.forEach(function (o) {
  25484. _this.scene.addParticleSystem(o);
  25485. });
  25486. this.animations.forEach(function (o) {
  25487. _this.scene.addAnimation(o);
  25488. });
  25489. this.multiMaterials.forEach(function (o) {
  25490. _this.scene.addMultiMaterial(o);
  25491. });
  25492. this.materials.forEach(function (o) {
  25493. _this.scene.addMaterial(o);
  25494. });
  25495. this.morphTargetManagers.forEach(function (o) {
  25496. _this.scene.addMorphTargetManager(o);
  25497. });
  25498. this.geometries.forEach(function (o) {
  25499. _this.scene.addGeometry(o);
  25500. });
  25501. this.transformNodes.forEach(function (o) {
  25502. _this.scene.addTransformNode(o);
  25503. });
  25504. this.lensFlareSystems.forEach(function (o) {
  25505. _this.scene.addLensFlareSystem(o);
  25506. });
  25507. this.actionManagers.forEach(function (o) {
  25508. _this.scene.addActionManager(o);
  25509. });
  25510. this.sounds.forEach(function (o) {
  25511. o.play();
  25512. o.autoplay = true;
  25513. _this.scene.mainSoundTrack.AddSound(o);
  25514. });
  25515. };
  25516. /**
  25517. * Removes all the assets in the container from the scene
  25518. */
  25519. AssetContainer.prototype.removeAllFromScene = function () {
  25520. var _this = this;
  25521. this.cameras.forEach(function (o) {
  25522. _this.scene.removeCamera(o);
  25523. });
  25524. this.lights.forEach(function (o) {
  25525. _this.scene.removeLight(o);
  25526. });
  25527. this.meshes.forEach(function (o) {
  25528. _this.scene.removeMesh(o);
  25529. });
  25530. this.skeletons.forEach(function (o) {
  25531. _this.scene.removeSkeleton(o);
  25532. });
  25533. this.particleSystems.forEach(function (o) {
  25534. _this.scene.removeParticleSystem(o);
  25535. });
  25536. this.animations.forEach(function (o) {
  25537. _this.scene.removeAnimation(o);
  25538. });
  25539. this.multiMaterials.forEach(function (o) {
  25540. _this.scene.removeMultiMaterial(o);
  25541. });
  25542. this.materials.forEach(function (o) {
  25543. _this.scene.removeMaterial(o);
  25544. });
  25545. this.morphTargetManagers.forEach(function (o) {
  25546. _this.scene.removeMorphTargetManager(o);
  25547. });
  25548. this.geometries.forEach(function (o) {
  25549. _this.scene.removeGeometry(o);
  25550. });
  25551. this.transformNodes.forEach(function (o) {
  25552. _this.scene.removeTransformNode(o);
  25553. });
  25554. this.lensFlareSystems.forEach(function (o) {
  25555. _this.scene.removeLensFlareSystem(o);
  25556. });
  25557. this.actionManagers.forEach(function (o) {
  25558. _this.scene.removeActionManager(o);
  25559. });
  25560. this.sounds.forEach(function (o) {
  25561. o.stop();
  25562. o.autoplay = false;
  25563. _this.scene.mainSoundTrack.RemoveSound(o);
  25564. });
  25565. };
  25566. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25567. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25568. var asset = sourceAssets_1[_i];
  25569. var move = true;
  25570. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25571. var keepAsset = keepAssets_1[_a];
  25572. if (asset === keepAsset) {
  25573. move = false;
  25574. break;
  25575. }
  25576. }
  25577. if (move) {
  25578. targetAssets.push(asset);
  25579. }
  25580. }
  25581. };
  25582. /**
  25583. * Removes all the assets contained in the scene and adds them to the container.
  25584. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25585. */
  25586. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25587. if (keepAssets === undefined) {
  25588. keepAssets = new KeepAssets();
  25589. }
  25590. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25591. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25592. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25593. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25594. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25595. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25596. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25597. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25598. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25599. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25600. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25601. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25602. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25603. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25604. this.removeAllFromScene();
  25605. };
  25606. return AssetContainer;
  25607. }());
  25608. BABYLON.AssetContainer = AssetContainer;
  25609. })(BABYLON || (BABYLON = {}));
  25610. //# sourceMappingURL=babylon.assetContainer.js.map
  25611. var BABYLON;
  25612. (function (BABYLON) {
  25613. var Buffer = /** @class */ (function () {
  25614. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25615. if (instanced === void 0) { instanced = false; }
  25616. if (engine instanceof BABYLON.Mesh) {
  25617. this._engine = engine.getScene().getEngine();
  25618. }
  25619. else {
  25620. this._engine = engine;
  25621. }
  25622. this._updatable = updatable;
  25623. this._instanced = instanced;
  25624. this._data = data;
  25625. this._strideSize = stride;
  25626. if (!postponeInternalCreation) {
  25627. this.create();
  25628. }
  25629. }
  25630. /**
  25631. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25632. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25633. * @param offset defines offset in the buffer (0 by default)
  25634. * @param size defines the size in floats of attributes (position is 3 for instance)
  25635. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25636. * @param instanced defines if the vertex buffer contains indexed data
  25637. * @returns the new vertex buffer
  25638. */
  25639. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25640. // a lot of these parameters are ignored as they are overriden by the buffer
  25641. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25642. };
  25643. // Properties
  25644. Buffer.prototype.isUpdatable = function () {
  25645. return this._updatable;
  25646. };
  25647. Buffer.prototype.getData = function () {
  25648. return this._data;
  25649. };
  25650. Buffer.prototype.getBuffer = function () {
  25651. return this._buffer;
  25652. };
  25653. Buffer.prototype.getStrideSize = function () {
  25654. return this._strideSize;
  25655. };
  25656. // public getIsInstanced(): boolean {
  25657. // return this._instanced;
  25658. // }
  25659. // public get instanceDivisor(): number {
  25660. // return this._instanceDivisor;
  25661. // }
  25662. // public set instanceDivisor(value: number) {
  25663. // this._instanceDivisor = value;
  25664. // if (value == 0) {
  25665. // this._instanced = false;
  25666. // } else {
  25667. // this._instanced = true;
  25668. // }
  25669. // }
  25670. // Methods
  25671. Buffer.prototype.create = function (data) {
  25672. if (data === void 0) { data = null; }
  25673. if (!data && this._buffer) {
  25674. return; // nothing to do
  25675. }
  25676. data = data || this._data;
  25677. if (!data) {
  25678. return;
  25679. }
  25680. if (!this._buffer) {
  25681. if (this._updatable) {
  25682. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25683. this._data = data;
  25684. }
  25685. else {
  25686. this._buffer = this._engine.createVertexBuffer(data);
  25687. }
  25688. }
  25689. else if (this._updatable) {
  25690. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25691. this._data = data;
  25692. }
  25693. };
  25694. Buffer.prototype._rebuild = function () {
  25695. this._buffer = null;
  25696. this.create(this._data);
  25697. };
  25698. Buffer.prototype.update = function (data) {
  25699. this.create(data);
  25700. };
  25701. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25702. if (!this._buffer) {
  25703. return;
  25704. }
  25705. if (this._updatable) {
  25706. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25707. this._data = null;
  25708. }
  25709. };
  25710. Buffer.prototype.dispose = function () {
  25711. if (!this._buffer) {
  25712. return;
  25713. }
  25714. if (this._engine._releaseBuffer(this._buffer)) {
  25715. this._buffer = null;
  25716. }
  25717. };
  25718. return Buffer;
  25719. }());
  25720. BABYLON.Buffer = Buffer;
  25721. })(BABYLON || (BABYLON = {}));
  25722. //# sourceMappingURL=babylon.buffer.js.map
  25723. var BABYLON;
  25724. (function (BABYLON) {
  25725. var VertexBuffer = /** @class */ (function () {
  25726. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25727. if (data instanceof BABYLON.Buffer) {
  25728. if (!stride) {
  25729. stride = data.getStrideSize();
  25730. }
  25731. this._buffer = data;
  25732. this._ownsBuffer = false;
  25733. }
  25734. else {
  25735. if (!stride) {
  25736. stride = VertexBuffer.DeduceStride(kind);
  25737. }
  25738. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25739. this._ownsBuffer = true;
  25740. }
  25741. this._stride = stride;
  25742. this._instanced = instanced !== undefined ? instanced : false;
  25743. this._instanceDivisor = instanced ? 1 : 0;
  25744. this._offset = offset ? offset : 0;
  25745. this._size = size ? size : stride;
  25746. this._kind = kind;
  25747. }
  25748. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25749. /**
  25750. * Gets or sets the instance divisor when in instanced mode
  25751. */
  25752. get: function () {
  25753. return this._instanceDivisor;
  25754. },
  25755. set: function (value) {
  25756. this._instanceDivisor = value;
  25757. if (value == 0) {
  25758. this._instanced = false;
  25759. }
  25760. else {
  25761. this._instanced = true;
  25762. }
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. VertexBuffer.prototype._rebuild = function () {
  25768. if (!this._buffer) {
  25769. return;
  25770. }
  25771. this._buffer._rebuild();
  25772. };
  25773. /**
  25774. * Returns the kind of the VertexBuffer (string).
  25775. */
  25776. VertexBuffer.prototype.getKind = function () {
  25777. return this._kind;
  25778. };
  25779. // Properties
  25780. /**
  25781. * Boolean : is the VertexBuffer updatable ?
  25782. */
  25783. VertexBuffer.prototype.isUpdatable = function () {
  25784. return this._buffer.isUpdatable();
  25785. };
  25786. /**
  25787. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25788. */
  25789. VertexBuffer.prototype.getData = function () {
  25790. return this._buffer.getData();
  25791. };
  25792. /**
  25793. * Returns the WebGLBuffer associated to the VertexBuffer.
  25794. */
  25795. VertexBuffer.prototype.getBuffer = function () {
  25796. return this._buffer.getBuffer();
  25797. };
  25798. /**
  25799. * Returns the stride of the VertexBuffer (integer).
  25800. */
  25801. VertexBuffer.prototype.getStrideSize = function () {
  25802. return this._stride;
  25803. };
  25804. /**
  25805. * Returns the offset (integer).
  25806. */
  25807. VertexBuffer.prototype.getOffset = function () {
  25808. return this._offset;
  25809. };
  25810. /**
  25811. * Returns the VertexBuffer total size (integer).
  25812. */
  25813. VertexBuffer.prototype.getSize = function () {
  25814. return this._size;
  25815. };
  25816. /**
  25817. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25818. */
  25819. VertexBuffer.prototype.getIsInstanced = function () {
  25820. return this._instanced;
  25821. };
  25822. /**
  25823. * Returns the instancing divisor, zero for non-instanced (integer).
  25824. */
  25825. VertexBuffer.prototype.getInstanceDivisor = function () {
  25826. return this._instanceDivisor;
  25827. };
  25828. // Methods
  25829. /**
  25830. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25831. * Returns the created WebGLBuffer.
  25832. */
  25833. VertexBuffer.prototype.create = function (data) {
  25834. return this._buffer.create(data);
  25835. };
  25836. /**
  25837. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25838. * This function will create a new buffer if the current one is not updatable
  25839. * Returns the updated WebGLBuffer.
  25840. */
  25841. VertexBuffer.prototype.update = function (data) {
  25842. return this._buffer.update(data);
  25843. };
  25844. /**
  25845. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25846. * Returns the directly updated WebGLBuffer.
  25847. */
  25848. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25849. return this._buffer.updateDirectly(data, offset);
  25850. };
  25851. /**
  25852. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25853. */
  25854. VertexBuffer.prototype.dispose = function () {
  25855. if (this._ownsBuffer) {
  25856. this._buffer.dispose();
  25857. }
  25858. };
  25859. Object.defineProperty(VertexBuffer, "PositionKind", {
  25860. get: function () {
  25861. return VertexBuffer._PositionKind;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(VertexBuffer, "NormalKind", {
  25867. get: function () {
  25868. return VertexBuffer._NormalKind;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(VertexBuffer, "TangentKind", {
  25874. get: function () {
  25875. return VertexBuffer._TangentKind;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(VertexBuffer, "UVKind", {
  25881. get: function () {
  25882. return VertexBuffer._UVKind;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25888. get: function () {
  25889. return VertexBuffer._UV2Kind;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25895. get: function () {
  25896. return VertexBuffer._UV3Kind;
  25897. },
  25898. enumerable: true,
  25899. configurable: true
  25900. });
  25901. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25902. get: function () {
  25903. return VertexBuffer._UV4Kind;
  25904. },
  25905. enumerable: true,
  25906. configurable: true
  25907. });
  25908. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25909. get: function () {
  25910. return VertexBuffer._UV5Kind;
  25911. },
  25912. enumerable: true,
  25913. configurable: true
  25914. });
  25915. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25916. get: function () {
  25917. return VertexBuffer._UV6Kind;
  25918. },
  25919. enumerable: true,
  25920. configurable: true
  25921. });
  25922. Object.defineProperty(VertexBuffer, "ColorKind", {
  25923. get: function () {
  25924. return VertexBuffer._ColorKind;
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25930. get: function () {
  25931. return VertexBuffer._MatricesIndicesKind;
  25932. },
  25933. enumerable: true,
  25934. configurable: true
  25935. });
  25936. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25937. get: function () {
  25938. return VertexBuffer._MatricesWeightsKind;
  25939. },
  25940. enumerable: true,
  25941. configurable: true
  25942. });
  25943. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25944. get: function () {
  25945. return VertexBuffer._MatricesIndicesExtraKind;
  25946. },
  25947. enumerable: true,
  25948. configurable: true
  25949. });
  25950. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25951. get: function () {
  25952. return VertexBuffer._MatricesWeightsExtraKind;
  25953. },
  25954. enumerable: true,
  25955. configurable: true
  25956. });
  25957. /**
  25958. * Deduces the stride given a kind.
  25959. * @param kind The kind string to deduce
  25960. * @returns The deduced stride
  25961. */
  25962. VertexBuffer.DeduceStride = function (kind) {
  25963. switch (kind) {
  25964. case VertexBuffer.UVKind:
  25965. case VertexBuffer.UV2Kind:
  25966. case VertexBuffer.UV3Kind:
  25967. case VertexBuffer.UV4Kind:
  25968. case VertexBuffer.UV5Kind:
  25969. case VertexBuffer.UV6Kind:
  25970. return 2;
  25971. case VertexBuffer.NormalKind:
  25972. case VertexBuffer.PositionKind:
  25973. return 3;
  25974. case VertexBuffer.ColorKind:
  25975. case VertexBuffer.MatricesIndicesKind:
  25976. case VertexBuffer.MatricesIndicesExtraKind:
  25977. case VertexBuffer.MatricesWeightsKind:
  25978. case VertexBuffer.MatricesWeightsExtraKind:
  25979. case VertexBuffer.TangentKind:
  25980. return 4;
  25981. default:
  25982. throw new Error("Invalid kind '" + kind + "'");
  25983. }
  25984. };
  25985. // Enums
  25986. VertexBuffer._PositionKind = "position";
  25987. VertexBuffer._NormalKind = "normal";
  25988. VertexBuffer._TangentKind = "tangent";
  25989. VertexBuffer._UVKind = "uv";
  25990. VertexBuffer._UV2Kind = "uv2";
  25991. VertexBuffer._UV3Kind = "uv3";
  25992. VertexBuffer._UV4Kind = "uv4";
  25993. VertexBuffer._UV5Kind = "uv5";
  25994. VertexBuffer._UV6Kind = "uv6";
  25995. VertexBuffer._ColorKind = "color";
  25996. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25997. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25998. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25999. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26000. return VertexBuffer;
  26001. }());
  26002. BABYLON.VertexBuffer = VertexBuffer;
  26003. })(BABYLON || (BABYLON = {}));
  26004. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26005. var BABYLON;
  26006. (function (BABYLON) {
  26007. /**
  26008. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26009. */
  26010. var DummyInternalTextureTracker = /** @class */ (function () {
  26011. function DummyInternalTextureTracker() {
  26012. /**
  26013. * Gets or set the previous tracker in the list
  26014. */
  26015. this.previous = null;
  26016. /**
  26017. * Gets or set the next tracker in the list
  26018. */
  26019. this.next = null;
  26020. }
  26021. return DummyInternalTextureTracker;
  26022. }());
  26023. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26024. })(BABYLON || (BABYLON = {}));
  26025. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26026. var BABYLON;
  26027. (function (BABYLON) {
  26028. /**
  26029. * Class used to store data associated with WebGL texture data for the engine
  26030. * This class should not be used directly
  26031. */
  26032. var InternalTexture = /** @class */ (function () {
  26033. /**
  26034. * Creates a new InternalTexture
  26035. * @param engine defines the engine to use
  26036. * @param dataSource defines the type of data that will be used
  26037. */
  26038. function InternalTexture(engine, dataSource) {
  26039. /**
  26040. * Observable called when the texture is loaded
  26041. */
  26042. this.onLoadedObservable = new BABYLON.Observable();
  26043. /**
  26044. * Gets or set the previous tracker in the list
  26045. */
  26046. this.previous = null;
  26047. /**
  26048. * Gets or set the next tracker in the list
  26049. */
  26050. this.next = null;
  26051. // Private
  26052. /** @ignore */
  26053. this._initialSlot = -1;
  26054. /** @ignore */
  26055. this._designatedSlot = -1;
  26056. /** @ignore */
  26057. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26058. /** @ignore */
  26059. this._comparisonFunction = 0;
  26060. /** @ignore */
  26061. this._references = 1;
  26062. this._engine = engine;
  26063. this._dataSource = dataSource;
  26064. this._webGLTexture = engine._createTexture();
  26065. }
  26066. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26067. /**
  26068. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26069. */
  26070. get: function () {
  26071. return this._dataSource;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. /**
  26077. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26078. */
  26079. InternalTexture.prototype.incrementReferences = function () {
  26080. this._references++;
  26081. };
  26082. /**
  26083. * Change the size of the texture (not the size of the content)
  26084. * @param width defines the new width
  26085. * @param height defines the new height
  26086. * @param depth defines the new depth (1 by default)
  26087. */
  26088. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26089. if (depth === void 0) { depth = 1; }
  26090. this.width = width;
  26091. this.height = height;
  26092. this.depth = depth;
  26093. this.baseWidth = width;
  26094. this.baseHeight = height;
  26095. this.baseDepth = depth;
  26096. this._size = width * height * depth;
  26097. };
  26098. /** @ignore */
  26099. InternalTexture.prototype._rebuild = function () {
  26100. var _this = this;
  26101. var proxy;
  26102. this.isReady = false;
  26103. this._cachedCoordinatesMode = null;
  26104. this._cachedWrapU = null;
  26105. this._cachedWrapV = null;
  26106. this._cachedAnisotropicFilteringLevel = null;
  26107. switch (this._dataSource) {
  26108. case InternalTexture.DATASOURCE_TEMP:
  26109. return;
  26110. case InternalTexture.DATASOURCE_URL:
  26111. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26112. _this.isReady = true;
  26113. }, null, this._buffer, undefined, this.format);
  26114. proxy._swapAndDie(this);
  26115. return;
  26116. case InternalTexture.DATASOURCE_RAW:
  26117. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26118. proxy._swapAndDie(this);
  26119. this.isReady = true;
  26120. return;
  26121. case InternalTexture.DATASOURCE_RAW3D:
  26122. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26123. proxy._swapAndDie(this);
  26124. this.isReady = true;
  26125. return;
  26126. case InternalTexture.DATASOURCE_DYNAMIC:
  26127. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26128. proxy._swapAndDie(this);
  26129. // The engine will make sure to update content so no need to flag it as isReady = true
  26130. return;
  26131. case InternalTexture.DATASOURCE_RENDERTARGET:
  26132. var options = new BABYLON.RenderTargetCreationOptions();
  26133. options.generateDepthBuffer = this._generateDepthBuffer;
  26134. options.generateMipMaps = this.generateMipMaps;
  26135. options.generateStencilBuffer = this._generateStencilBuffer;
  26136. options.samplingMode = this.samplingMode;
  26137. options.type = this.type;
  26138. if (this.isCube) {
  26139. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26140. }
  26141. else {
  26142. var size = {
  26143. width: this.width,
  26144. height: this.height
  26145. };
  26146. proxy = this._engine.createRenderTargetTexture(size, options);
  26147. }
  26148. proxy._swapAndDie(this);
  26149. this.isReady = true;
  26150. return;
  26151. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26152. var depthTextureOptions = {
  26153. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26154. comparisonFunction: this._comparisonFunction,
  26155. generateStencil: this._generateStencilBuffer,
  26156. };
  26157. if (this.isCube) {
  26158. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26159. }
  26160. else {
  26161. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26162. }
  26163. proxy._swapAndDie(this);
  26164. this.isReady = true;
  26165. return;
  26166. case InternalTexture.DATASOURCE_CUBE:
  26167. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26168. _this.isReady = true;
  26169. }, null, this.format, this._extension);
  26170. proxy._swapAndDie(this);
  26171. return;
  26172. case InternalTexture.DATASOURCE_CUBERAW:
  26173. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26174. proxy._swapAndDie(this);
  26175. this.isReady = true;
  26176. return;
  26177. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26178. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26179. if (proxy) {
  26180. proxy._swapAndDie(_this);
  26181. }
  26182. _this.isReady = true;
  26183. }, null, this.format, this._extension);
  26184. return;
  26185. }
  26186. };
  26187. InternalTexture.prototype._swapAndDie = function (target) {
  26188. target._webGLTexture = this._webGLTexture;
  26189. if (this._framebuffer) {
  26190. target._framebuffer = this._framebuffer;
  26191. }
  26192. if (this._depthStencilBuffer) {
  26193. target._depthStencilBuffer = this._depthStencilBuffer;
  26194. }
  26195. if (this._lodTextureHigh) {
  26196. if (target._lodTextureHigh) {
  26197. target._lodTextureHigh.dispose();
  26198. }
  26199. target._lodTextureHigh = this._lodTextureHigh;
  26200. }
  26201. if (this._lodTextureMid) {
  26202. if (target._lodTextureMid) {
  26203. target._lodTextureMid.dispose();
  26204. }
  26205. target._lodTextureMid = this._lodTextureMid;
  26206. }
  26207. if (this._lodTextureLow) {
  26208. if (target._lodTextureLow) {
  26209. target._lodTextureLow.dispose();
  26210. }
  26211. target._lodTextureLow = this._lodTextureLow;
  26212. }
  26213. var cache = this._engine.getLoadedTexturesCache();
  26214. var index = cache.indexOf(this);
  26215. if (index !== -1) {
  26216. cache.splice(index, 1);
  26217. }
  26218. };
  26219. /**
  26220. * Dispose the current allocated resources
  26221. */
  26222. InternalTexture.prototype.dispose = function () {
  26223. if (!this._webGLTexture) {
  26224. return;
  26225. }
  26226. this._references--;
  26227. if (this._references === 0) {
  26228. this._engine._releaseTexture(this);
  26229. this._webGLTexture = null;
  26230. this.previous = null;
  26231. this.next = null;
  26232. }
  26233. };
  26234. /**
  26235. * The source of the texture data is unknown
  26236. */
  26237. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26238. /**
  26239. * Texture data comes from an URL
  26240. */
  26241. InternalTexture.DATASOURCE_URL = 1;
  26242. /**
  26243. * Texture data is only used for temporary storage
  26244. */
  26245. InternalTexture.DATASOURCE_TEMP = 2;
  26246. /**
  26247. * Texture data comes from raw data (ArrayBuffer)
  26248. */
  26249. InternalTexture.DATASOURCE_RAW = 3;
  26250. /**
  26251. * Texture content is dynamic (video or dynamic texture)
  26252. */
  26253. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26254. /**
  26255. * Texture content is generated by rendering to it
  26256. */
  26257. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26258. /**
  26259. * Texture content is part of a multi render target process
  26260. */
  26261. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26262. /**
  26263. * Texture data comes from a cube data file
  26264. */
  26265. InternalTexture.DATASOURCE_CUBE = 7;
  26266. /**
  26267. * Texture data comes from a raw cube data
  26268. */
  26269. InternalTexture.DATASOURCE_CUBERAW = 8;
  26270. /**
  26271. * Texture data come from a prefiltered cube data file
  26272. */
  26273. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26274. /**
  26275. * Texture content is raw 3D data
  26276. */
  26277. InternalTexture.DATASOURCE_RAW3D = 10;
  26278. /**
  26279. * Texture content is a depth texture
  26280. */
  26281. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26282. return InternalTexture;
  26283. }());
  26284. BABYLON.InternalTexture = InternalTexture;
  26285. })(BABYLON || (BABYLON = {}));
  26286. //# sourceMappingURL=babylon.internalTexture.js.map
  26287. var BABYLON;
  26288. (function (BABYLON) {
  26289. var BaseTexture = /** @class */ (function () {
  26290. function BaseTexture(scene) {
  26291. this._hasAlpha = false;
  26292. this.getAlphaFromRGB = false;
  26293. this.level = 1;
  26294. this.coordinatesIndex = 0;
  26295. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26296. /**
  26297. * | Value | Type | Description |
  26298. * | ----- | ------------------ | ----------- |
  26299. * | 0 | CLAMP_ADDRESSMODE | |
  26300. * | 1 | WRAP_ADDRESSMODE | |
  26301. * | 2 | MIRROR_ADDRESSMODE | |
  26302. */
  26303. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26304. /**
  26305. * | Value | Type | Description |
  26306. * | ----- | ------------------ | ----------- |
  26307. * | 0 | CLAMP_ADDRESSMODE | |
  26308. * | 1 | WRAP_ADDRESSMODE | |
  26309. * | 2 | MIRROR_ADDRESSMODE | |
  26310. */
  26311. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26312. /**
  26313. * | Value | Type | Description |
  26314. * | ----- | ------------------ | ----------- |
  26315. * | 0 | CLAMP_ADDRESSMODE | |
  26316. * | 1 | WRAP_ADDRESSMODE | |
  26317. * | 2 | MIRROR_ADDRESSMODE | |
  26318. */
  26319. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26320. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26321. this.isCube = false;
  26322. this.is3D = false;
  26323. this.gammaSpace = true;
  26324. this.invertZ = false;
  26325. this.lodLevelInAlpha = false;
  26326. this.lodGenerationOffset = 0.0;
  26327. this.lodGenerationScale = 0.8;
  26328. this.isRenderTarget = false;
  26329. this.animations = new Array();
  26330. /**
  26331. * An event triggered when the texture is disposed.
  26332. * @type {BABYLON.Observable}
  26333. */
  26334. this.onDisposeObservable = new BABYLON.Observable();
  26335. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26336. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26337. if (this._scene) {
  26338. this._scene.textures.push(this);
  26339. }
  26340. this._uid = null;
  26341. }
  26342. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26343. get: function () {
  26344. return this._hasAlpha;
  26345. },
  26346. set: function (value) {
  26347. if (this._hasAlpha === value) {
  26348. return;
  26349. }
  26350. this._hasAlpha = value;
  26351. if (this._scene) {
  26352. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26353. }
  26354. },
  26355. enumerable: true,
  26356. configurable: true
  26357. });
  26358. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26359. get: function () {
  26360. return this._coordinatesMode;
  26361. },
  26362. /**
  26363. * How a texture is mapped.
  26364. *
  26365. * | Value | Type | Description |
  26366. * | ----- | ----------------------------------- | ----------- |
  26367. * | 0 | EXPLICIT_MODE | |
  26368. * | 1 | SPHERICAL_MODE | |
  26369. * | 2 | PLANAR_MODE | |
  26370. * | 3 | CUBIC_MODE | |
  26371. * | 4 | PROJECTION_MODE | |
  26372. * | 5 | SKYBOX_MODE | |
  26373. * | 6 | INVCUBIC_MODE | |
  26374. * | 7 | EQUIRECTANGULAR_MODE | |
  26375. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26376. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26377. */
  26378. set: function (value) {
  26379. if (this._coordinatesMode === value) {
  26380. return;
  26381. }
  26382. this._coordinatesMode = value;
  26383. if (this._scene) {
  26384. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26385. }
  26386. },
  26387. enumerable: true,
  26388. configurable: true
  26389. });
  26390. Object.defineProperty(BaseTexture.prototype, "uid", {
  26391. get: function () {
  26392. if (!this._uid) {
  26393. this._uid = BABYLON.Tools.RandomId();
  26394. }
  26395. return this._uid;
  26396. },
  26397. enumerable: true,
  26398. configurable: true
  26399. });
  26400. BaseTexture.prototype.toString = function () {
  26401. return this.name;
  26402. };
  26403. BaseTexture.prototype.getClassName = function () {
  26404. return "BaseTexture";
  26405. };
  26406. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26407. set: function (callback) {
  26408. if (this._onDisposeObserver) {
  26409. this.onDisposeObservable.remove(this._onDisposeObserver);
  26410. }
  26411. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26412. },
  26413. enumerable: true,
  26414. configurable: true
  26415. });
  26416. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26417. get: function () {
  26418. return true;
  26419. },
  26420. enumerable: true,
  26421. configurable: true
  26422. });
  26423. BaseTexture.prototype.getScene = function () {
  26424. return this._scene;
  26425. };
  26426. BaseTexture.prototype.getTextureMatrix = function () {
  26427. return BABYLON.Matrix.IdentityReadOnly;
  26428. };
  26429. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26430. return BABYLON.Matrix.IdentityReadOnly;
  26431. };
  26432. BaseTexture.prototype.getInternalTexture = function () {
  26433. return this._texture;
  26434. };
  26435. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26436. return !this.isBlocking || this.isReady();
  26437. };
  26438. BaseTexture.prototype.isReady = function () {
  26439. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26440. this.delayLoad();
  26441. return false;
  26442. }
  26443. if (this._texture) {
  26444. return this._texture.isReady;
  26445. }
  26446. return false;
  26447. };
  26448. BaseTexture.prototype.getSize = function () {
  26449. if (this._texture && this._texture.width) {
  26450. return new BABYLON.Size(this._texture.width, this._texture.height);
  26451. }
  26452. if (this._texture && this._texture._size) {
  26453. return new BABYLON.Size(this._texture._size, this._texture._size);
  26454. }
  26455. return BABYLON.Size.Zero();
  26456. };
  26457. BaseTexture.prototype.getBaseSize = function () {
  26458. if (!this.isReady() || !this._texture)
  26459. return BABYLON.Size.Zero();
  26460. if (this._texture._size) {
  26461. return new BABYLON.Size(this._texture._size, this._texture._size);
  26462. }
  26463. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26464. };
  26465. BaseTexture.prototype.scale = function (ratio) {
  26466. };
  26467. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26468. get: function () {
  26469. return false;
  26470. },
  26471. enumerable: true,
  26472. configurable: true
  26473. });
  26474. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26475. if (!this._scene) {
  26476. return null;
  26477. }
  26478. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26479. for (var index = 0; index < texturesCache.length; index++) {
  26480. var texturesCacheEntry = texturesCache[index];
  26481. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26482. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26483. texturesCacheEntry.incrementReferences();
  26484. return texturesCacheEntry;
  26485. }
  26486. }
  26487. }
  26488. return null;
  26489. };
  26490. BaseTexture.prototype._rebuild = function () {
  26491. };
  26492. BaseTexture.prototype.delayLoad = function () {
  26493. };
  26494. BaseTexture.prototype.clone = function () {
  26495. return null;
  26496. };
  26497. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26498. get: function () {
  26499. if (!this._texture) {
  26500. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26501. }
  26502. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26503. },
  26504. enumerable: true,
  26505. configurable: true
  26506. });
  26507. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26508. get: function () {
  26509. if (!this._texture) {
  26510. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26511. }
  26512. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26513. },
  26514. enumerable: true,
  26515. configurable: true
  26516. });
  26517. BaseTexture.prototype.readPixels = function (faceIndex) {
  26518. if (faceIndex === void 0) { faceIndex = 0; }
  26519. if (!this._texture) {
  26520. return null;
  26521. }
  26522. var size = this.getSize();
  26523. var scene = this.getScene();
  26524. if (!scene) {
  26525. return null;
  26526. }
  26527. var engine = scene.getEngine();
  26528. if (this._texture.isCube) {
  26529. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26530. }
  26531. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26532. };
  26533. BaseTexture.prototype.releaseInternalTexture = function () {
  26534. if (this._texture) {
  26535. this._texture.dispose();
  26536. this._texture = null;
  26537. }
  26538. };
  26539. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26540. get: function () {
  26541. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26542. return null;
  26543. }
  26544. if (!this._texture._sphericalPolynomial) {
  26545. this._texture._sphericalPolynomial =
  26546. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26547. }
  26548. return this._texture._sphericalPolynomial;
  26549. },
  26550. set: function (value) {
  26551. if (this._texture) {
  26552. this._texture._sphericalPolynomial = value;
  26553. }
  26554. },
  26555. enumerable: true,
  26556. configurable: true
  26557. });
  26558. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26559. get: function () {
  26560. if (this._texture) {
  26561. return this._texture._lodTextureHigh;
  26562. }
  26563. return null;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26569. get: function () {
  26570. if (this._texture) {
  26571. return this._texture._lodTextureMid;
  26572. }
  26573. return null;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26579. get: function () {
  26580. if (this._texture) {
  26581. return this._texture._lodTextureLow;
  26582. }
  26583. return null;
  26584. },
  26585. enumerable: true,
  26586. configurable: true
  26587. });
  26588. BaseTexture.prototype.dispose = function () {
  26589. if (!this._scene) {
  26590. return;
  26591. }
  26592. // Animations
  26593. this._scene.stopAnimation(this);
  26594. // Remove from scene
  26595. this._scene._removePendingData(this);
  26596. var index = this._scene.textures.indexOf(this);
  26597. if (index >= 0) {
  26598. this._scene.textures.splice(index, 1);
  26599. }
  26600. if (this._texture === undefined) {
  26601. return;
  26602. }
  26603. // Release
  26604. this.releaseInternalTexture();
  26605. // Callback
  26606. this.onDisposeObservable.notifyObservers(this);
  26607. this.onDisposeObservable.clear();
  26608. };
  26609. BaseTexture.prototype.serialize = function () {
  26610. if (!this.name) {
  26611. return null;
  26612. }
  26613. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26614. // Animations
  26615. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26616. return serializationObject;
  26617. };
  26618. BaseTexture.WhenAllReady = function (textures, callback) {
  26619. var numRemaining = textures.length;
  26620. if (numRemaining === 0) {
  26621. callback();
  26622. return;
  26623. }
  26624. var _loop_1 = function () {
  26625. texture = textures[i];
  26626. if (texture.isReady()) {
  26627. if (--numRemaining === 0) {
  26628. callback();
  26629. }
  26630. }
  26631. else {
  26632. onLoadObservable = texture.onLoadObservable;
  26633. var onLoadCallback_1 = function () {
  26634. onLoadObservable.removeCallback(onLoadCallback_1);
  26635. if (--numRemaining === 0) {
  26636. callback();
  26637. }
  26638. };
  26639. onLoadObservable.add(onLoadCallback_1);
  26640. }
  26641. };
  26642. var texture, onLoadObservable;
  26643. for (var i = 0; i < textures.length; i++) {
  26644. _loop_1();
  26645. }
  26646. };
  26647. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26648. __decorate([
  26649. BABYLON.serialize()
  26650. ], BaseTexture.prototype, "name", void 0);
  26651. __decorate([
  26652. BABYLON.serialize("hasAlpha")
  26653. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26654. __decorate([
  26655. BABYLON.serialize()
  26656. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26657. __decorate([
  26658. BABYLON.serialize()
  26659. ], BaseTexture.prototype, "level", void 0);
  26660. __decorate([
  26661. BABYLON.serialize()
  26662. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26663. __decorate([
  26664. BABYLON.serialize("coordinatesMode")
  26665. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26666. __decorate([
  26667. BABYLON.serialize()
  26668. ], BaseTexture.prototype, "wrapU", void 0);
  26669. __decorate([
  26670. BABYLON.serialize()
  26671. ], BaseTexture.prototype, "wrapV", void 0);
  26672. __decorate([
  26673. BABYLON.serialize()
  26674. ], BaseTexture.prototype, "wrapR", void 0);
  26675. __decorate([
  26676. BABYLON.serialize()
  26677. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26678. __decorate([
  26679. BABYLON.serialize()
  26680. ], BaseTexture.prototype, "isCube", void 0);
  26681. __decorate([
  26682. BABYLON.serialize()
  26683. ], BaseTexture.prototype, "is3D", void 0);
  26684. __decorate([
  26685. BABYLON.serialize()
  26686. ], BaseTexture.prototype, "gammaSpace", void 0);
  26687. __decorate([
  26688. BABYLON.serialize()
  26689. ], BaseTexture.prototype, "invertZ", void 0);
  26690. __decorate([
  26691. BABYLON.serialize()
  26692. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26693. __decorate([
  26694. BABYLON.serialize()
  26695. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26696. __decorate([
  26697. BABYLON.serialize()
  26698. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26699. __decorate([
  26700. BABYLON.serialize()
  26701. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26702. return BaseTexture;
  26703. }());
  26704. BABYLON.BaseTexture = BaseTexture;
  26705. })(BABYLON || (BABYLON = {}));
  26706. //# sourceMappingURL=babylon.baseTexture.js.map
  26707. var BABYLON;
  26708. (function (BABYLON) {
  26709. var Texture = /** @class */ (function (_super) {
  26710. __extends(Texture, _super);
  26711. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26712. if (noMipmap === void 0) { noMipmap = false; }
  26713. if (invertY === void 0) { invertY = true; }
  26714. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26715. if (onLoad === void 0) { onLoad = null; }
  26716. if (onError === void 0) { onError = null; }
  26717. if (buffer === void 0) { buffer = null; }
  26718. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26719. var _this = _super.call(this, scene) || this;
  26720. _this.uOffset = 0;
  26721. _this.vOffset = 0;
  26722. _this.uScale = 1.0;
  26723. _this.vScale = 1.0;
  26724. _this.uAng = 0;
  26725. _this.vAng = 0;
  26726. _this.wAng = 0;
  26727. _this._isBlocking = true;
  26728. _this.name = url || "";
  26729. _this.url = url;
  26730. _this._noMipmap = noMipmap;
  26731. _this._invertY = invertY;
  26732. _this._samplingMode = samplingMode;
  26733. _this._buffer = buffer;
  26734. _this._deleteBuffer = deleteBuffer;
  26735. if (format) {
  26736. _this._format = format;
  26737. }
  26738. scene = _this.getScene();
  26739. if (!scene) {
  26740. return _this;
  26741. }
  26742. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26743. var load = function () {
  26744. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26745. _this.onLoadObservable.notifyObservers(_this);
  26746. }
  26747. if (onLoad) {
  26748. onLoad();
  26749. }
  26750. if (!_this.isBlocking && scene) {
  26751. scene.resetCachedMaterial();
  26752. }
  26753. };
  26754. if (!_this.url) {
  26755. _this._delayedOnLoad = load;
  26756. _this._delayedOnError = onError;
  26757. return _this;
  26758. }
  26759. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26760. if (!_this._texture) {
  26761. if (!scene.useDelayedTextureLoading) {
  26762. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26763. if (deleteBuffer) {
  26764. delete _this._buffer;
  26765. }
  26766. }
  26767. else {
  26768. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26769. _this._delayedOnLoad = load;
  26770. _this._delayedOnError = onError;
  26771. }
  26772. }
  26773. else {
  26774. if (_this._texture.isReady) {
  26775. BABYLON.Tools.SetImmediate(function () { return load(); });
  26776. }
  26777. else {
  26778. _this._texture.onLoadedObservable.add(load);
  26779. }
  26780. }
  26781. return _this;
  26782. }
  26783. Object.defineProperty(Texture.prototype, "noMipmap", {
  26784. get: function () {
  26785. return this._noMipmap;
  26786. },
  26787. enumerable: true,
  26788. configurable: true
  26789. });
  26790. Object.defineProperty(Texture.prototype, "isBlocking", {
  26791. get: function () {
  26792. return this._isBlocking;
  26793. },
  26794. set: function (value) {
  26795. this._isBlocking = value;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. Object.defineProperty(Texture.prototype, "samplingMode", {
  26801. get: function () {
  26802. return this._samplingMode;
  26803. },
  26804. enumerable: true,
  26805. configurable: true
  26806. });
  26807. Texture.prototype.updateURL = function (url) {
  26808. this.url = url;
  26809. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26810. this.delayLoad();
  26811. };
  26812. Texture.prototype.delayLoad = function () {
  26813. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26814. return;
  26815. }
  26816. var scene = this.getScene();
  26817. if (!scene) {
  26818. return;
  26819. }
  26820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26821. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26822. if (!this._texture) {
  26823. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26824. if (this._deleteBuffer) {
  26825. delete this._buffer;
  26826. }
  26827. }
  26828. else {
  26829. if (this._delayedOnLoad) {
  26830. if (this._texture.isReady) {
  26831. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26832. }
  26833. else {
  26834. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26835. }
  26836. }
  26837. }
  26838. this._delayedOnLoad = null;
  26839. this._delayedOnError = null;
  26840. };
  26841. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26842. if (!this._texture) {
  26843. return;
  26844. }
  26845. var scene = this.getScene();
  26846. if (!scene) {
  26847. return;
  26848. }
  26849. this._samplingMode = samplingMode;
  26850. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26851. };
  26852. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26853. x *= this.uScale;
  26854. y *= this.vScale;
  26855. x -= 0.5 * this.uScale;
  26856. y -= 0.5 * this.vScale;
  26857. z -= 0.5;
  26858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26859. t.x += 0.5 * this.uScale + this.uOffset;
  26860. t.y += 0.5 * this.vScale + this.vOffset;
  26861. t.z += 0.5;
  26862. };
  26863. Texture.prototype.getTextureMatrix = function () {
  26864. var _this = this;
  26865. if (this.uOffset === this._cachedUOffset &&
  26866. this.vOffset === this._cachedVOffset &&
  26867. this.uScale === this._cachedUScale &&
  26868. this.vScale === this._cachedVScale &&
  26869. this.uAng === this._cachedUAng &&
  26870. this.vAng === this._cachedVAng &&
  26871. this.wAng === this._cachedWAng) {
  26872. return this._cachedTextureMatrix;
  26873. }
  26874. this._cachedUOffset = this.uOffset;
  26875. this._cachedVOffset = this.vOffset;
  26876. this._cachedUScale = this.uScale;
  26877. this._cachedVScale = this.vScale;
  26878. this._cachedUAng = this.uAng;
  26879. this._cachedVAng = this.vAng;
  26880. this._cachedWAng = this.wAng;
  26881. if (!this._cachedTextureMatrix) {
  26882. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26883. this._rowGenerationMatrix = new BABYLON.Matrix();
  26884. this._t0 = BABYLON.Vector3.Zero();
  26885. this._t1 = BABYLON.Vector3.Zero();
  26886. this._t2 = BABYLON.Vector3.Zero();
  26887. }
  26888. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26889. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26890. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26891. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26892. this._t1.subtractInPlace(this._t0);
  26893. this._t2.subtractInPlace(this._t0);
  26894. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26895. this._cachedTextureMatrix.m[0] = this._t1.x;
  26896. this._cachedTextureMatrix.m[1] = this._t1.y;
  26897. this._cachedTextureMatrix.m[2] = this._t1.z;
  26898. this._cachedTextureMatrix.m[4] = this._t2.x;
  26899. this._cachedTextureMatrix.m[5] = this._t2.y;
  26900. this._cachedTextureMatrix.m[6] = this._t2.z;
  26901. this._cachedTextureMatrix.m[8] = this._t0.x;
  26902. this._cachedTextureMatrix.m[9] = this._t0.y;
  26903. this._cachedTextureMatrix.m[10] = this._t0.z;
  26904. var scene = this.getScene();
  26905. if (!scene) {
  26906. return this._cachedTextureMatrix;
  26907. }
  26908. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26909. return mat.hasTexture(_this);
  26910. });
  26911. return this._cachedTextureMatrix;
  26912. };
  26913. Texture.prototype.getReflectionTextureMatrix = function () {
  26914. var _this = this;
  26915. var scene = this.getScene();
  26916. if (!scene) {
  26917. return this._cachedTextureMatrix;
  26918. }
  26919. if (this.uOffset === this._cachedUOffset &&
  26920. this.vOffset === this._cachedVOffset &&
  26921. this.uScale === this._cachedUScale &&
  26922. this.vScale === this._cachedVScale &&
  26923. this.coordinatesMode === this._cachedCoordinatesMode) {
  26924. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26925. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26926. return this._cachedTextureMatrix;
  26927. }
  26928. }
  26929. else {
  26930. return this._cachedTextureMatrix;
  26931. }
  26932. }
  26933. if (!this._cachedTextureMatrix) {
  26934. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26935. }
  26936. if (!this._projectionModeMatrix) {
  26937. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26938. }
  26939. this._cachedUOffset = this.uOffset;
  26940. this._cachedVOffset = this.vOffset;
  26941. this._cachedUScale = this.uScale;
  26942. this._cachedVScale = this.vScale;
  26943. this._cachedCoordinatesMode = this.coordinatesMode;
  26944. switch (this.coordinatesMode) {
  26945. case Texture.PLANAR_MODE:
  26946. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26947. this._cachedTextureMatrix[0] = this.uScale;
  26948. this._cachedTextureMatrix[5] = this.vScale;
  26949. this._cachedTextureMatrix[12] = this.uOffset;
  26950. this._cachedTextureMatrix[13] = this.vOffset;
  26951. break;
  26952. case Texture.PROJECTION_MODE:
  26953. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26954. this._projectionModeMatrix.m[0] = 0.5;
  26955. this._projectionModeMatrix.m[5] = -0.5;
  26956. this._projectionModeMatrix.m[10] = 0.0;
  26957. this._projectionModeMatrix.m[12] = 0.5;
  26958. this._projectionModeMatrix.m[13] = 0.5;
  26959. this._projectionModeMatrix.m[14] = 1.0;
  26960. this._projectionModeMatrix.m[15] = 1.0;
  26961. var projectionMatrix = scene.getProjectionMatrix();
  26962. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26963. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26964. break;
  26965. default:
  26966. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26967. break;
  26968. }
  26969. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26970. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26971. });
  26972. return this._cachedTextureMatrix;
  26973. };
  26974. Texture.prototype.clone = function () {
  26975. var _this = this;
  26976. return BABYLON.SerializationHelper.Clone(function () {
  26977. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26978. }, this);
  26979. };
  26980. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26981. get: function () {
  26982. if (!this._onLoadObservable) {
  26983. this._onLoadObservable = new BABYLON.Observable();
  26984. }
  26985. return this._onLoadObservable;
  26986. },
  26987. enumerable: true,
  26988. configurable: true
  26989. });
  26990. Texture.prototype.serialize = function () {
  26991. var serializationObject = _super.prototype.serialize.call(this);
  26992. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26993. serializationObject.base64String = this._buffer;
  26994. serializationObject.name = serializationObject.name.replace("data:", "");
  26995. }
  26996. return serializationObject;
  26997. };
  26998. Texture.prototype.getClassName = function () {
  26999. return "Texture";
  27000. };
  27001. Texture.prototype.dispose = function () {
  27002. _super.prototype.dispose.call(this);
  27003. if (this.onLoadObservable) {
  27004. this.onLoadObservable.clear();
  27005. this._onLoadObservable = null;
  27006. }
  27007. this._delayedOnLoad = null;
  27008. this._delayedOnError = null;
  27009. };
  27010. // Statics
  27011. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27012. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27013. if (onLoad === void 0) { onLoad = null; }
  27014. if (onError === void 0) { onError = null; }
  27015. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27016. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27017. };
  27018. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27019. if (parsedTexture.customType) {
  27020. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27021. // Update Sampling Mode
  27022. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27023. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27024. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27025. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27026. }
  27027. }
  27028. return parsedCustomTexture;
  27029. }
  27030. if (parsedTexture.isCube) {
  27031. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27032. }
  27033. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27034. return null;
  27035. }
  27036. var texture = BABYLON.SerializationHelper.Parse(function () {
  27037. var generateMipMaps = true;
  27038. if (parsedTexture.noMipmap) {
  27039. generateMipMaps = false;
  27040. }
  27041. if (parsedTexture.mirrorPlane) {
  27042. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27043. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27044. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27045. return mirrorTexture;
  27046. }
  27047. else if (parsedTexture.isRenderTarget) {
  27048. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27049. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27050. return renderTargetTexture;
  27051. }
  27052. else {
  27053. var texture;
  27054. if (parsedTexture.base64String) {
  27055. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27056. }
  27057. else {
  27058. var url = rootUrl + parsedTexture.name;
  27059. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27060. url = parsedTexture.url;
  27061. }
  27062. texture = new Texture(url, scene, !generateMipMaps);
  27063. }
  27064. return texture;
  27065. }
  27066. }, parsedTexture, scene);
  27067. // Update Sampling Mode
  27068. if (parsedTexture.samplingMode) {
  27069. var sampling = parsedTexture.samplingMode;
  27070. if (texture._samplingMode !== sampling) {
  27071. texture.updateSamplingMode(sampling);
  27072. }
  27073. }
  27074. // Animations
  27075. if (parsedTexture.animations) {
  27076. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27077. var parsedAnimation = parsedTexture.animations[animationIndex];
  27078. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27079. }
  27080. }
  27081. return texture;
  27082. };
  27083. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27084. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27085. if (noMipmap === void 0) { noMipmap = false; }
  27086. if (invertY === void 0) { invertY = true; }
  27087. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27088. if (onLoad === void 0) { onLoad = null; }
  27089. if (onError === void 0) { onError = null; }
  27090. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27091. if (name.substr(0, 5) !== "data:") {
  27092. name = "data:" + name;
  27093. }
  27094. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27095. };
  27096. // Constants
  27097. Texture.NEAREST_SAMPLINGMODE = 1;
  27098. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27099. Texture.BILINEAR_SAMPLINGMODE = 2;
  27100. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27101. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27102. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27103. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27104. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27105. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27106. Texture.NEAREST_LINEAR = 7;
  27107. Texture.NEAREST_NEAREST = 8;
  27108. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27109. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27110. Texture.LINEAR_LINEAR = 11;
  27111. Texture.LINEAR_NEAREST = 12;
  27112. Texture.EXPLICIT_MODE = 0;
  27113. Texture.SPHERICAL_MODE = 1;
  27114. Texture.PLANAR_MODE = 2;
  27115. Texture.CUBIC_MODE = 3;
  27116. Texture.PROJECTION_MODE = 4;
  27117. Texture.SKYBOX_MODE = 5;
  27118. Texture.INVCUBIC_MODE = 6;
  27119. Texture.EQUIRECTANGULAR_MODE = 7;
  27120. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27121. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27122. Texture.CLAMP_ADDRESSMODE = 0;
  27123. Texture.WRAP_ADDRESSMODE = 1;
  27124. Texture.MIRROR_ADDRESSMODE = 2;
  27125. /**
  27126. * 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
  27127. */
  27128. Texture.UseSerializedUrlIfAny = false;
  27129. __decorate([
  27130. BABYLON.serialize()
  27131. ], Texture.prototype, "url", void 0);
  27132. __decorate([
  27133. BABYLON.serialize()
  27134. ], Texture.prototype, "uOffset", void 0);
  27135. __decorate([
  27136. BABYLON.serialize()
  27137. ], Texture.prototype, "vOffset", void 0);
  27138. __decorate([
  27139. BABYLON.serialize()
  27140. ], Texture.prototype, "uScale", void 0);
  27141. __decorate([
  27142. BABYLON.serialize()
  27143. ], Texture.prototype, "vScale", void 0);
  27144. __decorate([
  27145. BABYLON.serialize()
  27146. ], Texture.prototype, "uAng", void 0);
  27147. __decorate([
  27148. BABYLON.serialize()
  27149. ], Texture.prototype, "vAng", void 0);
  27150. __decorate([
  27151. BABYLON.serialize()
  27152. ], Texture.prototype, "wAng", void 0);
  27153. __decorate([
  27154. BABYLON.serialize()
  27155. ], Texture.prototype, "isBlocking", null);
  27156. return Texture;
  27157. }(BABYLON.BaseTexture));
  27158. BABYLON.Texture = Texture;
  27159. })(BABYLON || (BABYLON = {}));
  27160. //# sourceMappingURL=babylon.texture.js.map
  27161. var BABYLON;
  27162. (function (BABYLON) {
  27163. var _InstancesBatch = /** @class */ (function () {
  27164. function _InstancesBatch() {
  27165. this.mustReturn = false;
  27166. this.visibleInstances = new Array();
  27167. this.renderSelf = new Array();
  27168. }
  27169. return _InstancesBatch;
  27170. }());
  27171. BABYLON._InstancesBatch = _InstancesBatch;
  27172. var Mesh = /** @class */ (function (_super) {
  27173. __extends(Mesh, _super);
  27174. /**
  27175. * @constructor
  27176. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27177. * @param {Scene} scene The scene to add this mesh to.
  27178. * @param {Node} parent The parent of this mesh, if it has one
  27179. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27180. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27181. * When false, achieved by calling a clone(), also passing False.
  27182. * This will make creation of children, recursive.
  27183. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27184. */
  27185. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27186. if (scene === void 0) { scene = null; }
  27187. if (parent === void 0) { parent = null; }
  27188. if (source === void 0) { source = null; }
  27189. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27190. var _this = _super.call(this, name, scene) || this;
  27191. // Events
  27192. /**
  27193. * An event triggered before rendering the mesh
  27194. * @type {BABYLON.Observable}
  27195. */
  27196. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27197. /**
  27198. * An event triggered after rendering the mesh
  27199. * @type {BABYLON.Observable}
  27200. */
  27201. _this.onAfterRenderObservable = new BABYLON.Observable();
  27202. /**
  27203. * An event triggered before drawing the mesh
  27204. * @type {BABYLON.Observable}
  27205. */
  27206. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27207. // Members
  27208. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27209. _this.instances = new Array();
  27210. _this._LODLevels = new Array();
  27211. _this._visibleInstances = {};
  27212. _this._renderIdForInstances = new Array();
  27213. _this._batchCache = new _InstancesBatch();
  27214. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27215. // Use by builder only to know what orientation were the mesh build in.
  27216. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27217. _this.overrideMaterialSideOrientation = null;
  27218. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27219. // Will be used to save a source mesh reference, If any
  27220. _this._source = null;
  27221. scene = _this.getScene();
  27222. if (source) {
  27223. // Source mesh
  27224. _this._source = source;
  27225. // Geometry
  27226. if (source._geometry) {
  27227. source._geometry.applyToMesh(_this);
  27228. }
  27229. // Deep copy
  27230. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27231. // Metadata
  27232. if (source.metadata && source.metadata.clone) {
  27233. _this.metadata = source.metadata.clone();
  27234. }
  27235. else {
  27236. _this.metadata = source.metadata;
  27237. }
  27238. // Tags
  27239. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27240. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27241. }
  27242. // Parent
  27243. _this.parent = source.parent;
  27244. // Pivot
  27245. _this.setPivotMatrix(source.getPivotMatrix());
  27246. _this.id = name + "." + source.id;
  27247. // Material
  27248. _this.material = source.material;
  27249. var index;
  27250. if (!doNotCloneChildren) {
  27251. // Children
  27252. var directDescendants = source.getDescendants(true);
  27253. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27254. var child = directDescendants[index_1];
  27255. if (child.clone) {
  27256. child.clone(name + "." + child.name, _this);
  27257. }
  27258. }
  27259. }
  27260. // Physics clone
  27261. var physicsEngine = _this.getScene().getPhysicsEngine();
  27262. if (clonePhysicsImpostor && physicsEngine) {
  27263. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27264. if (impostor) {
  27265. _this.physicsImpostor = impostor.clone(_this);
  27266. }
  27267. }
  27268. // Particles
  27269. for (index = 0; index < scene.particleSystems.length; index++) {
  27270. var system = scene.particleSystems[index];
  27271. if (system.emitter === source) {
  27272. system.clone(system.name, _this);
  27273. }
  27274. }
  27275. _this.computeWorldMatrix(true);
  27276. }
  27277. // Parent
  27278. if (parent !== null) {
  27279. _this.parent = parent;
  27280. }
  27281. return _this;
  27282. }
  27283. Object.defineProperty(Mesh, "FRONTSIDE", {
  27284. /**
  27285. * Mesh side orientation : usually the external or front surface
  27286. */
  27287. get: function () {
  27288. return Mesh._FRONTSIDE;
  27289. },
  27290. enumerable: true,
  27291. configurable: true
  27292. });
  27293. Object.defineProperty(Mesh, "BACKSIDE", {
  27294. /**
  27295. * Mesh side orientation : usually the internal or back surface
  27296. */
  27297. get: function () {
  27298. return Mesh._BACKSIDE;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27304. /**
  27305. * Mesh side orientation : both internal and external or front and back surfaces
  27306. */
  27307. get: function () {
  27308. return Mesh._DOUBLESIDE;
  27309. },
  27310. enumerable: true,
  27311. configurable: true
  27312. });
  27313. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27314. /**
  27315. * Mesh side orientation : by default, `FRONTSIDE`
  27316. */
  27317. get: function () {
  27318. return Mesh._DEFAULTSIDE;
  27319. },
  27320. enumerable: true,
  27321. configurable: true
  27322. });
  27323. Object.defineProperty(Mesh, "NO_CAP", {
  27324. /**
  27325. * Mesh cap setting : no cap
  27326. */
  27327. get: function () {
  27328. return Mesh._NO_CAP;
  27329. },
  27330. enumerable: true,
  27331. configurable: true
  27332. });
  27333. Object.defineProperty(Mesh, "CAP_START", {
  27334. /**
  27335. * Mesh cap setting : one cap at the beginning of the mesh
  27336. */
  27337. get: function () {
  27338. return Mesh._CAP_START;
  27339. },
  27340. enumerable: true,
  27341. configurable: true
  27342. });
  27343. Object.defineProperty(Mesh, "CAP_END", {
  27344. /**
  27345. * Mesh cap setting : one cap at the end of the mesh
  27346. */
  27347. get: function () {
  27348. return Mesh._CAP_END;
  27349. },
  27350. enumerable: true,
  27351. configurable: true
  27352. });
  27353. Object.defineProperty(Mesh, "CAP_ALL", {
  27354. /**
  27355. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27356. */
  27357. get: function () {
  27358. return Mesh._CAP_ALL;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27364. set: function (callback) {
  27365. if (this._onBeforeDrawObserver) {
  27366. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27367. }
  27368. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27369. },
  27370. enumerable: true,
  27371. configurable: true
  27372. });
  27373. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27374. get: function () {
  27375. return this._morphTargetManager;
  27376. },
  27377. set: function (value) {
  27378. if (this._morphTargetManager === value) {
  27379. return;
  27380. }
  27381. this._morphTargetManager = value;
  27382. this._syncGeometryWithMorphTargetManager();
  27383. },
  27384. enumerable: true,
  27385. configurable: true
  27386. });
  27387. Object.defineProperty(Mesh.prototype, "source", {
  27388. get: function () {
  27389. return this._source;
  27390. },
  27391. enumerable: true,
  27392. configurable: true
  27393. });
  27394. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27395. get: function () {
  27396. return this._unIndexed;
  27397. },
  27398. set: function (value) {
  27399. if (this._unIndexed !== value) {
  27400. this._unIndexed = value;
  27401. this._markSubMeshesAsAttributesDirty();
  27402. }
  27403. },
  27404. enumerable: true,
  27405. configurable: true
  27406. });
  27407. // Methods
  27408. /**
  27409. * Returns the string "Mesh".
  27410. */
  27411. Mesh.prototype.getClassName = function () {
  27412. return "Mesh";
  27413. };
  27414. /**
  27415. * Returns a string.
  27416. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27417. */
  27418. Mesh.prototype.toString = function (fullDetails) {
  27419. var ret = _super.prototype.toString.call(this, fullDetails);
  27420. ret += ", n vertices: " + this.getTotalVertices();
  27421. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27422. if (this.animations) {
  27423. for (var i = 0; i < this.animations.length; i++) {
  27424. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27425. }
  27426. }
  27427. if (fullDetails) {
  27428. if (this._geometry) {
  27429. var ib = this.getIndices();
  27430. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27431. if (vb && ib) {
  27432. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27433. }
  27434. }
  27435. else {
  27436. ret += ", flat shading: UNKNOWN";
  27437. }
  27438. }
  27439. return ret;
  27440. };
  27441. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27442. /**
  27443. * True if the mesh has some Levels Of Details (LOD).
  27444. * Returns a boolean.
  27445. */
  27446. get: function () {
  27447. return this._LODLevels.length > 0;
  27448. },
  27449. enumerable: true,
  27450. configurable: true
  27451. });
  27452. /**
  27453. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27454. * @returns an array of {BABYLON.MeshLODLevel}
  27455. */
  27456. Mesh.prototype.getLODLevels = function () {
  27457. return this._LODLevels;
  27458. };
  27459. Mesh.prototype._sortLODLevels = function () {
  27460. this._LODLevels.sort(function (a, b) {
  27461. if (a.distance < b.distance) {
  27462. return 1;
  27463. }
  27464. if (a.distance > b.distance) {
  27465. return -1;
  27466. }
  27467. return 0;
  27468. });
  27469. };
  27470. /**
  27471. * Add a mesh as LOD level triggered at the given distance.
  27472. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27473. * @param {number} distance The distance from the center of the object to show this level
  27474. * @param {Mesh} mesh The mesh to be added as LOD level
  27475. * @return {Mesh} This mesh (for chaining)
  27476. */
  27477. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27478. if (mesh && mesh._masterMesh) {
  27479. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27480. return this;
  27481. }
  27482. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27483. this._LODLevels.push(level);
  27484. if (mesh) {
  27485. mesh._masterMesh = this;
  27486. }
  27487. this._sortLODLevels();
  27488. return this;
  27489. };
  27490. /**
  27491. * Returns the LOD level mesh at the passed distance or null if not found.
  27492. * It is related to the method `addLODLevel(distance, mesh)`.
  27493. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27494. * Returns an object Mesh or `null`.
  27495. */
  27496. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27497. for (var index = 0; index < this._LODLevels.length; index++) {
  27498. var level = this._LODLevels[index];
  27499. if (level.distance === distance) {
  27500. return level.mesh;
  27501. }
  27502. }
  27503. return null;
  27504. };
  27505. /**
  27506. * Remove a mesh from the LOD array
  27507. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27508. * @param {Mesh} mesh The mesh to be removed.
  27509. * @return {Mesh} This mesh (for chaining)
  27510. */
  27511. Mesh.prototype.removeLODLevel = function (mesh) {
  27512. for (var index = 0; index < this._LODLevels.length; index++) {
  27513. if (this._LODLevels[index].mesh === mesh) {
  27514. this._LODLevels.splice(index, 1);
  27515. if (mesh) {
  27516. mesh._masterMesh = null;
  27517. }
  27518. }
  27519. }
  27520. this._sortLODLevels();
  27521. return this;
  27522. };
  27523. /**
  27524. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27525. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27526. */
  27527. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27528. if (!this._LODLevels || this._LODLevels.length === 0) {
  27529. return this;
  27530. }
  27531. var bSphere;
  27532. if (boundingSphere) {
  27533. bSphere = boundingSphere;
  27534. }
  27535. else {
  27536. var boundingInfo = this.getBoundingInfo();
  27537. bSphere = boundingInfo.boundingSphere;
  27538. }
  27539. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27540. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27541. if (this.onLODLevelSelection) {
  27542. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27543. }
  27544. return this;
  27545. }
  27546. for (var index = 0; index < this._LODLevels.length; index++) {
  27547. var level = this._LODLevels[index];
  27548. if (level.distance < distanceToCamera) {
  27549. if (level.mesh) {
  27550. level.mesh._preActivate();
  27551. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27552. }
  27553. if (this.onLODLevelSelection) {
  27554. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27555. }
  27556. return level.mesh;
  27557. }
  27558. }
  27559. if (this.onLODLevelSelection) {
  27560. this.onLODLevelSelection(distanceToCamera, this, this);
  27561. }
  27562. return this;
  27563. };
  27564. Object.defineProperty(Mesh.prototype, "geometry", {
  27565. /**
  27566. * Returns the mesh internal Geometry object.
  27567. */
  27568. get: function () {
  27569. return this._geometry;
  27570. },
  27571. enumerable: true,
  27572. configurable: true
  27573. });
  27574. /**
  27575. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27576. */
  27577. Mesh.prototype.getTotalVertices = function () {
  27578. if (this._geometry === null || this._geometry === undefined) {
  27579. return 0;
  27580. }
  27581. return this._geometry.getTotalVertices();
  27582. };
  27583. /**
  27584. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27585. * 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.
  27586. * You can force the copy with forceCopy === true
  27587. * Returns null if the mesh has no geometry or no vertex buffer.
  27588. * Possible `kind` values :
  27589. * - BABYLON.VertexBuffer.PositionKind
  27590. * - BABYLON.VertexBuffer.UVKind
  27591. * - BABYLON.VertexBuffer.UV2Kind
  27592. * - BABYLON.VertexBuffer.UV3Kind
  27593. * - BABYLON.VertexBuffer.UV4Kind
  27594. * - BABYLON.VertexBuffer.UV5Kind
  27595. * - BABYLON.VertexBuffer.UV6Kind
  27596. * - BABYLON.VertexBuffer.ColorKind
  27597. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27598. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27599. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27600. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27601. */
  27602. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27603. if (!this._geometry) {
  27604. return null;
  27605. }
  27606. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27607. };
  27608. /**
  27609. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27610. * Returns `null` if the mesh has no geometry.
  27611. * Possible `kind` values :
  27612. * - BABYLON.VertexBuffer.PositionKind
  27613. * - BABYLON.VertexBuffer.UVKind
  27614. * - BABYLON.VertexBuffer.UV2Kind
  27615. * - BABYLON.VertexBuffer.UV3Kind
  27616. * - BABYLON.VertexBuffer.UV4Kind
  27617. * - BABYLON.VertexBuffer.UV5Kind
  27618. * - BABYLON.VertexBuffer.UV6Kind
  27619. * - BABYLON.VertexBuffer.ColorKind
  27620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27624. */
  27625. Mesh.prototype.getVertexBuffer = function (kind) {
  27626. if (!this._geometry) {
  27627. return null;
  27628. }
  27629. return this._geometry.getVertexBuffer(kind);
  27630. };
  27631. /**
  27632. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27633. * Possible `kind` values :
  27634. * - BABYLON.VertexBuffer.PositionKind
  27635. * - BABYLON.VertexBuffer.UVKind
  27636. * - BABYLON.VertexBuffer.UV2Kind
  27637. * - BABYLON.VertexBuffer.UV3Kind
  27638. * - BABYLON.VertexBuffer.UV4Kind
  27639. * - BABYLON.VertexBuffer.UV5Kind
  27640. * - BABYLON.VertexBuffer.UV6Kind
  27641. * - BABYLON.VertexBuffer.ColorKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27646. */
  27647. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27648. if (!this._geometry) {
  27649. if (this._delayInfo) {
  27650. return this._delayInfo.indexOf(kind) !== -1;
  27651. }
  27652. return false;
  27653. }
  27654. return this._geometry.isVerticesDataPresent(kind);
  27655. };
  27656. /**
  27657. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27658. * Possible `kind` values :
  27659. * - BABYLON.VertexBuffer.PositionKind
  27660. * - BABYLON.VertexBuffer.UVKind
  27661. * - BABYLON.VertexBuffer.UV2Kind
  27662. * - BABYLON.VertexBuffer.UV3Kind
  27663. * - BABYLON.VertexBuffer.UV4Kind
  27664. * - BABYLON.VertexBuffer.UV5Kind
  27665. * - BABYLON.VertexBuffer.UV6Kind
  27666. * - BABYLON.VertexBuffer.ColorKind
  27667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27671. */
  27672. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27673. if (!this._geometry) {
  27674. if (this._delayInfo) {
  27675. return this._delayInfo.indexOf(kind) !== -1;
  27676. }
  27677. return false;
  27678. }
  27679. return this._geometry.isVertexBufferUpdatable(kind);
  27680. };
  27681. /**
  27682. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27683. * Possible `kind` values :
  27684. * - BABYLON.VertexBuffer.PositionKind
  27685. * - BABYLON.VertexBuffer.UVKind
  27686. * - BABYLON.VertexBuffer.UV2Kind
  27687. * - BABYLON.VertexBuffer.UV3Kind
  27688. * - BABYLON.VertexBuffer.UV4Kind
  27689. * - BABYLON.VertexBuffer.UV5Kind
  27690. * - BABYLON.VertexBuffer.UV6Kind
  27691. * - BABYLON.VertexBuffer.ColorKind
  27692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27696. */
  27697. Mesh.prototype.getVerticesDataKinds = function () {
  27698. if (!this._geometry) {
  27699. var result = new Array();
  27700. if (this._delayInfo) {
  27701. this._delayInfo.forEach(function (kind, index, array) {
  27702. result.push(kind);
  27703. });
  27704. }
  27705. return result;
  27706. }
  27707. return this._geometry.getVerticesDataKinds();
  27708. };
  27709. /**
  27710. * Returns a positive integer : the total number of indices in this mesh geometry.
  27711. * Returns zero if the mesh has no geometry.
  27712. */
  27713. Mesh.prototype.getTotalIndices = function () {
  27714. if (!this._geometry) {
  27715. return 0;
  27716. }
  27717. return this._geometry.getTotalIndices();
  27718. };
  27719. /**
  27720. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27721. * 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.
  27722. * Returns an empty array if the mesh has no geometry.
  27723. */
  27724. Mesh.prototype.getIndices = function (copyWhenShared) {
  27725. if (!this._geometry) {
  27726. return [];
  27727. }
  27728. return this._geometry.getIndices(copyWhenShared);
  27729. };
  27730. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27731. get: function () {
  27732. return this._masterMesh !== null && this._masterMesh !== undefined;
  27733. },
  27734. enumerable: true,
  27735. configurable: true
  27736. });
  27737. /**
  27738. * Determine if the current mesh is ready to be rendered
  27739. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27740. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27741. * @returns true if all associated assets are ready (material, textures, shaders)
  27742. */
  27743. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27744. if (completeCheck === void 0) { completeCheck = false; }
  27745. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27746. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27747. return false;
  27748. }
  27749. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27750. return false;
  27751. }
  27752. if (!this.subMeshes || this.subMeshes.length === 0) {
  27753. return true;
  27754. }
  27755. if (!completeCheck) {
  27756. return true;
  27757. }
  27758. var engine = this.getEngine();
  27759. var scene = this.getScene();
  27760. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27761. this.computeWorldMatrix();
  27762. var mat = this.material || scene.defaultMaterial;
  27763. if (mat) {
  27764. if (mat.storeEffectOnSubMeshes) {
  27765. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27766. var subMesh = _a[_i];
  27767. var effectiveMaterial = subMesh.getMaterial();
  27768. if (effectiveMaterial) {
  27769. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27770. return false;
  27771. }
  27772. }
  27773. }
  27774. }
  27775. else {
  27776. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27777. return false;
  27778. }
  27779. }
  27780. }
  27781. // Shadows
  27782. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27783. var light = _c[_b];
  27784. var generator = light.getShadowGenerator();
  27785. if (generator) {
  27786. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27787. var subMesh = _e[_d];
  27788. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27789. return false;
  27790. }
  27791. }
  27792. }
  27793. }
  27794. // LOD
  27795. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27796. var lod = _g[_f];
  27797. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27798. return false;
  27799. }
  27800. }
  27801. return true;
  27802. };
  27803. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27804. /**
  27805. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27806. * This property is pertinent only for updatable parametric shapes.
  27807. */
  27808. get: function () {
  27809. return this._areNormalsFrozen;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. /**
  27815. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27816. * It has no effect at all on other shapes.
  27817. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27818. * Returns the Mesh.
  27819. */
  27820. Mesh.prototype.freezeNormals = function () {
  27821. this._areNormalsFrozen = true;
  27822. return this;
  27823. };
  27824. /**
  27825. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27826. * It has no effect at all on other shapes.
  27827. * It reactivates the mesh normals computation if it was previously frozen.
  27828. * Returns the Mesh.
  27829. */
  27830. Mesh.prototype.unfreezeNormals = function () {
  27831. this._areNormalsFrozen = false;
  27832. return this;
  27833. };
  27834. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27835. /**
  27836. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27837. */
  27838. set: function (count) {
  27839. this._overridenInstanceCount = count;
  27840. },
  27841. enumerable: true,
  27842. configurable: true
  27843. });
  27844. // Methods
  27845. Mesh.prototype._preActivate = function () {
  27846. var sceneRenderId = this.getScene().getRenderId();
  27847. if (this._preActivateId === sceneRenderId) {
  27848. return this;
  27849. }
  27850. this._preActivateId = sceneRenderId;
  27851. this._visibleInstances = null;
  27852. return this;
  27853. };
  27854. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27855. if (this._visibleInstances) {
  27856. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27857. }
  27858. return this;
  27859. };
  27860. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27861. if (!this._visibleInstances) {
  27862. this._visibleInstances = {};
  27863. this._visibleInstances.defaultRenderId = renderId;
  27864. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27865. }
  27866. if (!this._visibleInstances[renderId]) {
  27867. this._visibleInstances[renderId] = new Array();
  27868. }
  27869. this._visibleInstances[renderId].push(instance);
  27870. return this;
  27871. };
  27872. /**
  27873. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27874. * This means the mesh underlying bounding box and sphere are recomputed.
  27875. * Returns the Mesh.
  27876. */
  27877. Mesh.prototype.refreshBoundingInfo = function () {
  27878. return this._refreshBoundingInfo(false);
  27879. };
  27880. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27881. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27882. return this;
  27883. }
  27884. var data = this._getPositionData(applySkeleton);
  27885. if (data) {
  27886. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27887. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27888. }
  27889. if (this.subMeshes) {
  27890. for (var index = 0; index < this.subMeshes.length; index++) {
  27891. this.subMeshes[index].refreshBoundingInfo();
  27892. }
  27893. }
  27894. this._updateBoundingInfo();
  27895. return this;
  27896. };
  27897. Mesh.prototype._getPositionData = function (applySkeleton) {
  27898. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27899. if (data && applySkeleton && this.skeleton) {
  27900. data = BABYLON.Tools.Slice(data);
  27901. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27902. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27903. if (matricesWeightsData && matricesIndicesData) {
  27904. var needExtras = this.numBoneInfluencers > 4;
  27905. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27906. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27907. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27908. var tempVector = BABYLON.Tmp.Vector3[0];
  27909. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27910. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27911. var matWeightIdx = 0;
  27912. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27913. finalMatrix.reset();
  27914. var inf;
  27915. var weight;
  27916. for (inf = 0; inf < 4; inf++) {
  27917. weight = matricesWeightsData[matWeightIdx + inf];
  27918. if (weight <= 0)
  27919. break;
  27920. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27921. finalMatrix.addToSelf(tempMatrix);
  27922. }
  27923. if (needExtras) {
  27924. for (inf = 0; inf < 4; inf++) {
  27925. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27926. if (weight <= 0)
  27927. break;
  27928. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27929. finalMatrix.addToSelf(tempMatrix);
  27930. }
  27931. }
  27932. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27933. tempVector.toArray(data, index);
  27934. }
  27935. }
  27936. }
  27937. return data;
  27938. };
  27939. Mesh.prototype._createGlobalSubMesh = function (force) {
  27940. var totalVertices = this.getTotalVertices();
  27941. if (!totalVertices || !this.getIndices()) {
  27942. return null;
  27943. }
  27944. // Check if we need to recreate the submeshes
  27945. if (this.subMeshes && this.subMeshes.length > 0) {
  27946. var ib = this.getIndices();
  27947. if (!ib) {
  27948. return null;
  27949. }
  27950. var totalIndices = ib.length;
  27951. var needToRecreate = false;
  27952. if (force) {
  27953. needToRecreate = true;
  27954. }
  27955. else {
  27956. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27957. var submesh = _a[_i];
  27958. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27959. needToRecreate = true;
  27960. break;
  27961. }
  27962. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27963. needToRecreate = true;
  27964. break;
  27965. }
  27966. }
  27967. }
  27968. if (!needToRecreate) {
  27969. return this.subMeshes[0];
  27970. }
  27971. }
  27972. this.releaseSubMeshes();
  27973. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27974. };
  27975. Mesh.prototype.subdivide = function (count) {
  27976. if (count < 1) {
  27977. return;
  27978. }
  27979. var totalIndices = this.getTotalIndices();
  27980. var subdivisionSize = (totalIndices / count) | 0;
  27981. var offset = 0;
  27982. // Ensure that subdivisionSize is a multiple of 3
  27983. while (subdivisionSize % 3 !== 0) {
  27984. subdivisionSize++;
  27985. }
  27986. this.releaseSubMeshes();
  27987. for (var index = 0; index < count; index++) {
  27988. if (offset >= totalIndices) {
  27989. break;
  27990. }
  27991. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27992. offset += subdivisionSize;
  27993. }
  27994. this.synchronizeInstances();
  27995. };
  27996. /**
  27997. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27998. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27999. * The `data` are either a numeric array either a Float32Array.
  28000. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28001. * 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).
  28002. * Note that a new underlying VertexBuffer object is created each call.
  28003. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28004. *
  28005. * Possible `kind` values :
  28006. * - BABYLON.VertexBuffer.PositionKind
  28007. * - BABYLON.VertexBuffer.UVKind
  28008. * - BABYLON.VertexBuffer.UV2Kind
  28009. * - BABYLON.VertexBuffer.UV3Kind
  28010. * - BABYLON.VertexBuffer.UV4Kind
  28011. * - BABYLON.VertexBuffer.UV5Kind
  28012. * - BABYLON.VertexBuffer.UV6Kind
  28013. * - BABYLON.VertexBuffer.ColorKind
  28014. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28015. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28016. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28017. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28018. *
  28019. * Returns the Mesh.
  28020. */
  28021. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28022. if (updatable === void 0) { updatable = false; }
  28023. if (!this._geometry) {
  28024. var vertexData = new BABYLON.VertexData();
  28025. vertexData.set(data, kind);
  28026. var scene = this.getScene();
  28027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28028. }
  28029. else {
  28030. this._geometry.setVerticesData(kind, data, updatable, stride);
  28031. }
  28032. return this;
  28033. };
  28034. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28035. if (updatable === void 0) { updatable = true; }
  28036. var vb = this.getVertexBuffer(kind);
  28037. if (!vb || vb.isUpdatable() === updatable) {
  28038. return;
  28039. }
  28040. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28041. };
  28042. /**
  28043. * Sets the mesh VertexBuffer.
  28044. * Returns the Mesh.
  28045. */
  28046. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28047. if (!this._geometry) {
  28048. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28049. }
  28050. this._geometry.setVerticesBuffer(buffer);
  28051. return this;
  28052. };
  28053. /**
  28054. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28055. * If the mesh has no geometry, it is simply returned as it is.
  28056. * The `data` are either a numeric array either a Float32Array.
  28057. * No new underlying VertexBuffer object is created.
  28058. * 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.
  28059. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28060. *
  28061. * Possible `kind` values :
  28062. * - BABYLON.VertexBuffer.PositionKind
  28063. * - BABYLON.VertexBuffer.UVKind
  28064. * - BABYLON.VertexBuffer.UV2Kind
  28065. * - BABYLON.VertexBuffer.UV3Kind
  28066. * - BABYLON.VertexBuffer.UV4Kind
  28067. * - BABYLON.VertexBuffer.UV5Kind
  28068. * - BABYLON.VertexBuffer.UV6Kind
  28069. * - BABYLON.VertexBuffer.ColorKind
  28070. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28071. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28072. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28073. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28074. *
  28075. * Returns the Mesh.
  28076. */
  28077. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28078. if (!this._geometry) {
  28079. return this;
  28080. }
  28081. if (!makeItUnique) {
  28082. this._geometry.updateVerticesData(kind, data, updateExtends);
  28083. }
  28084. else {
  28085. this.makeGeometryUnique();
  28086. this.updateVerticesData(kind, data, updateExtends, false);
  28087. }
  28088. return this;
  28089. };
  28090. /**
  28091. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28092. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28093. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28094. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28095. * Returns the Mesh.
  28096. */
  28097. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28098. if (computeNormals === void 0) { computeNormals = true; }
  28099. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28100. if (!positions) {
  28101. return this;
  28102. }
  28103. positionFunction(positions);
  28104. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28105. if (computeNormals) {
  28106. var indices = this.getIndices();
  28107. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28108. if (!normals) {
  28109. return this;
  28110. }
  28111. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28112. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28113. }
  28114. return this;
  28115. };
  28116. /**
  28117. * Creates a un-shared specific occurence of the geometry for the mesh.
  28118. * Returns the Mesh.
  28119. */
  28120. Mesh.prototype.makeGeometryUnique = function () {
  28121. if (!this._geometry) {
  28122. return this;
  28123. }
  28124. var oldGeometry = this._geometry;
  28125. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28126. oldGeometry.releaseForMesh(this, true);
  28127. geometry.applyToMesh(this);
  28128. return this;
  28129. };
  28130. /**
  28131. * Sets the mesh indices.
  28132. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28133. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28134. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28135. * This method creates a new index buffer each call.
  28136. * Returns the Mesh.
  28137. */
  28138. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28139. if (totalVertices === void 0) { totalVertices = null; }
  28140. if (updatable === void 0) { updatable = false; }
  28141. if (!this._geometry) {
  28142. var vertexData = new BABYLON.VertexData();
  28143. vertexData.indices = indices;
  28144. var scene = this.getScene();
  28145. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28146. }
  28147. else {
  28148. this._geometry.setIndices(indices, totalVertices, updatable);
  28149. }
  28150. return this;
  28151. };
  28152. /**
  28153. * Update the current index buffer
  28154. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28155. * Returns the Mesh.
  28156. */
  28157. Mesh.prototype.updateIndices = function (indices, offset) {
  28158. if (!this._geometry) {
  28159. return this;
  28160. }
  28161. this._geometry.updateIndices(indices, offset);
  28162. return this;
  28163. };
  28164. /**
  28165. * Invert the geometry to move from a right handed system to a left handed one.
  28166. * Returns the Mesh.
  28167. */
  28168. Mesh.prototype.toLeftHanded = function () {
  28169. if (!this._geometry) {
  28170. return this;
  28171. }
  28172. this._geometry.toLeftHanded();
  28173. return this;
  28174. };
  28175. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28176. if (!this._geometry) {
  28177. return this;
  28178. }
  28179. var engine = this.getScene().getEngine();
  28180. // Wireframe
  28181. var indexToBind;
  28182. if (this._unIndexed) {
  28183. indexToBind = null;
  28184. }
  28185. else {
  28186. switch (fillMode) {
  28187. case BABYLON.Material.PointFillMode:
  28188. indexToBind = null;
  28189. break;
  28190. case BABYLON.Material.WireFrameFillMode:
  28191. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28192. break;
  28193. default:
  28194. case BABYLON.Material.TriangleFillMode:
  28195. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28196. break;
  28197. }
  28198. }
  28199. // VBOs
  28200. this._geometry._bind(effect, indexToBind);
  28201. return this;
  28202. };
  28203. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28204. if (alternate === void 0) { alternate = false; }
  28205. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28206. return this;
  28207. }
  28208. this.onBeforeDrawObservable.notifyObservers(this);
  28209. var scene = this.getScene();
  28210. var engine = scene.getEngine();
  28211. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28212. // or triangles as points
  28213. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28214. }
  28215. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28216. // Triangles as wireframe
  28217. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28218. }
  28219. else {
  28220. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28221. }
  28222. if (scene._isAlternateRenderingEnabled && !alternate) {
  28223. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28224. if (!effect || !scene.activeCamera) {
  28225. return this;
  28226. }
  28227. scene._switchToAlternateCameraConfiguration(true);
  28228. this._effectiveMaterial.bindView(effect);
  28229. this._effectiveMaterial.bindViewProjection(effect);
  28230. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28231. this._draw(subMesh, fillMode, instancesCount, true);
  28232. engine.setViewport(scene.activeCamera.viewport);
  28233. scene._switchToAlternateCameraConfiguration(false);
  28234. this._effectiveMaterial.bindView(effect);
  28235. this._effectiveMaterial.bindViewProjection(effect);
  28236. }
  28237. return this;
  28238. };
  28239. /**
  28240. * Registers for this mesh a javascript function called just before the rendering process.
  28241. * This function is passed the current mesh.
  28242. * Return the Mesh.
  28243. */
  28244. Mesh.prototype.registerBeforeRender = function (func) {
  28245. this.onBeforeRenderObservable.add(func);
  28246. return this;
  28247. };
  28248. /**
  28249. * Disposes a previously registered javascript function called before the rendering.
  28250. * This function is passed the current mesh.
  28251. * Returns the Mesh.
  28252. */
  28253. Mesh.prototype.unregisterBeforeRender = function (func) {
  28254. this.onBeforeRenderObservable.removeCallback(func);
  28255. return this;
  28256. };
  28257. /**
  28258. * Registers for this mesh a javascript function called just after the rendering is complete.
  28259. * This function is passed the current mesh.
  28260. * Returns the Mesh.
  28261. */
  28262. Mesh.prototype.registerAfterRender = function (func) {
  28263. this.onAfterRenderObservable.add(func);
  28264. return this;
  28265. };
  28266. /**
  28267. * Disposes a previously registered javascript function called after the rendering.
  28268. * This function is passed the current mesh.
  28269. * Return the Mesh.
  28270. */
  28271. Mesh.prototype.unregisterAfterRender = function (func) {
  28272. this.onAfterRenderObservable.removeCallback(func);
  28273. return this;
  28274. };
  28275. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28276. var scene = this.getScene();
  28277. this._batchCache.mustReturn = false;
  28278. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28279. this._batchCache.visibleInstances[subMeshId] = null;
  28280. if (this._visibleInstances) {
  28281. var currentRenderId = scene.getRenderId();
  28282. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28283. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28284. var selfRenderId = this._renderId;
  28285. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28286. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28287. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28288. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28289. }
  28290. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28291. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28292. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28293. this._batchCache.mustReturn = true;
  28294. return this._batchCache;
  28295. }
  28296. if (currentRenderId !== selfRenderId) {
  28297. this._batchCache.renderSelf[subMeshId] = false;
  28298. }
  28299. }
  28300. this._renderIdForInstances[subMeshId] = currentRenderId;
  28301. }
  28302. return this._batchCache;
  28303. };
  28304. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28305. var visibleInstances = batch.visibleInstances[subMesh._id];
  28306. if (!visibleInstances) {
  28307. return this;
  28308. }
  28309. var matricesCount = visibleInstances.length + 1;
  28310. var bufferSize = matricesCount * 16 * 4;
  28311. var currentInstancesBufferSize = this._instancesBufferSize;
  28312. var instancesBuffer = this._instancesBuffer;
  28313. while (this._instancesBufferSize < bufferSize) {
  28314. this._instancesBufferSize *= 2;
  28315. }
  28316. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28317. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28318. }
  28319. var offset = 0;
  28320. var instancesCount = 0;
  28321. var world = this.getWorldMatrix();
  28322. if (batch.renderSelf[subMesh._id]) {
  28323. world.copyToArray(this._instancesData, offset);
  28324. offset += 16;
  28325. instancesCount++;
  28326. }
  28327. if (visibleInstances) {
  28328. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28329. var instance = visibleInstances[instanceIndex];
  28330. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28331. offset += 16;
  28332. instancesCount++;
  28333. }
  28334. }
  28335. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28336. if (instancesBuffer) {
  28337. instancesBuffer.dispose();
  28338. }
  28339. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28340. this._instancesBuffer = instancesBuffer;
  28341. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28342. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28343. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28344. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28345. }
  28346. else {
  28347. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28348. }
  28349. this._bind(subMesh, effect, fillMode);
  28350. this._draw(subMesh, fillMode, instancesCount);
  28351. engine.unbindInstanceAttributes();
  28352. return this;
  28353. };
  28354. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28355. var scene = this.getScene();
  28356. var engine = scene.getEngine();
  28357. if (hardwareInstancedRendering) {
  28358. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28359. }
  28360. else {
  28361. if (batch.renderSelf[subMesh._id]) {
  28362. // Draw
  28363. if (onBeforeDraw) {
  28364. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28365. }
  28366. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28367. }
  28368. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28369. if (visibleInstancesForSubMesh) {
  28370. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28371. var instance = visibleInstancesForSubMesh[instanceIndex];
  28372. // World
  28373. var world = instance.getWorldMatrix();
  28374. if (onBeforeDraw) {
  28375. onBeforeDraw(true, world, effectiveMaterial);
  28376. }
  28377. // Draw
  28378. this._draw(subMesh, fillMode);
  28379. }
  28380. }
  28381. }
  28382. return this;
  28383. };
  28384. /**
  28385. * Triggers the draw call for the mesh.
  28386. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28387. * Returns the Mesh.
  28388. */
  28389. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28390. this.checkOcclusionQuery();
  28391. if (this._isOccluded) {
  28392. return this;
  28393. }
  28394. var scene = this.getScene();
  28395. // Managing instances
  28396. var batch = this._getInstancesRenderList(subMesh._id);
  28397. if (batch.mustReturn) {
  28398. return this;
  28399. }
  28400. // Checking geometry state
  28401. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28402. return this;
  28403. }
  28404. this.onBeforeRenderObservable.notifyObservers(this);
  28405. var engine = scene.getEngine();
  28406. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28407. // Material
  28408. var material = subMesh.getMaterial();
  28409. if (!material) {
  28410. return this;
  28411. }
  28412. this._effectiveMaterial = material;
  28413. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28414. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28415. return this;
  28416. }
  28417. }
  28418. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28419. return this;
  28420. }
  28421. // Alpha mode
  28422. if (enableAlphaMode) {
  28423. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28424. }
  28425. // Outline - step 1
  28426. var savedDepthWrite = engine.getDepthWrite();
  28427. if (this.renderOutline) {
  28428. engine.setDepthWrite(false);
  28429. scene.getOutlineRenderer().render(subMesh, batch);
  28430. engine.setDepthWrite(savedDepthWrite);
  28431. }
  28432. var effect;
  28433. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28434. effect = subMesh.effect;
  28435. }
  28436. else {
  28437. effect = this._effectiveMaterial.getEffect();
  28438. }
  28439. if (!effect) {
  28440. return this;
  28441. }
  28442. var sideOrientation = this.overrideMaterialSideOrientation;
  28443. if (sideOrientation == null) {
  28444. sideOrientation = this._effectiveMaterial.sideOrientation;
  28445. if (this._getWorldMatrixDeterminant() < 0) {
  28446. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28447. }
  28448. }
  28449. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28450. if (this._effectiveMaterial.forceDepthWrite) {
  28451. engine.setDepthWrite(true);
  28452. }
  28453. // Bind
  28454. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28455. if (!hardwareInstancedRendering) {
  28456. this._bind(subMesh, effect, fillMode);
  28457. }
  28458. var world = this.getWorldMatrix();
  28459. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28460. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28461. }
  28462. else {
  28463. this._effectiveMaterial.bind(world, this);
  28464. }
  28465. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28466. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28467. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28468. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28469. }
  28470. // Draw
  28471. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28472. // Unbind
  28473. this._effectiveMaterial.unbind();
  28474. // Outline - step 2
  28475. if (this.renderOutline && savedDepthWrite) {
  28476. engine.setDepthWrite(true);
  28477. engine.setColorWrite(false);
  28478. scene.getOutlineRenderer().render(subMesh, batch);
  28479. engine.setColorWrite(true);
  28480. }
  28481. // Overlay
  28482. if (this.renderOverlay) {
  28483. var currentMode = engine.getAlphaMode();
  28484. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28485. scene.getOutlineRenderer().render(subMesh, batch, true);
  28486. engine.setAlphaMode(currentMode);
  28487. }
  28488. this.onAfterRenderObservable.notifyObservers(this);
  28489. return this;
  28490. };
  28491. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28492. if (isInstance && effectiveMaterial) {
  28493. effectiveMaterial.bindOnlyWorldMatrix(world);
  28494. }
  28495. };
  28496. /**
  28497. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28498. */
  28499. Mesh.prototype.getEmittedParticleSystems = function () {
  28500. var results = new Array();
  28501. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28502. var particleSystem = this.getScene().particleSystems[index];
  28503. if (particleSystem.emitter === this) {
  28504. results.push(particleSystem);
  28505. }
  28506. }
  28507. return results;
  28508. };
  28509. /**
  28510. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28511. */
  28512. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28513. var results = new Array();
  28514. var descendants = this.getDescendants();
  28515. descendants.push(this);
  28516. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28517. var particleSystem = this.getScene().particleSystems[index];
  28518. var emitter = particleSystem.emitter;
  28519. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28520. results.push(particleSystem);
  28521. }
  28522. }
  28523. return results;
  28524. };
  28525. Mesh.prototype._checkDelayState = function () {
  28526. var scene = this.getScene();
  28527. if (this._geometry) {
  28528. this._geometry.load(scene);
  28529. }
  28530. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28532. this._queueLoad(scene);
  28533. }
  28534. return this;
  28535. };
  28536. Mesh.prototype._queueLoad = function (scene) {
  28537. var _this = this;
  28538. scene._addPendingData(this);
  28539. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28540. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28541. if (data instanceof ArrayBuffer) {
  28542. _this._delayLoadingFunction(data, _this);
  28543. }
  28544. else {
  28545. _this._delayLoadingFunction(JSON.parse(data), _this);
  28546. }
  28547. _this.instances.forEach(function (instance) {
  28548. instance._syncSubMeshes();
  28549. });
  28550. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28551. scene._removePendingData(_this);
  28552. }, function () { }, scene.database, getBinaryData);
  28553. return this;
  28554. };
  28555. /**
  28556. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28557. */
  28558. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28559. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28560. return false;
  28561. }
  28562. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28563. return false;
  28564. }
  28565. this._checkDelayState();
  28566. return true;
  28567. };
  28568. /**
  28569. * Sets the mesh material by the material or multiMaterial `id` property.
  28570. * The material `id` is a string identifying the material or the multiMaterial.
  28571. * This method returns the Mesh.
  28572. */
  28573. Mesh.prototype.setMaterialByID = function (id) {
  28574. var materials = this.getScene().materials;
  28575. var index;
  28576. for (index = materials.length - 1; index > -1; index--) {
  28577. if (materials[index].id === id) {
  28578. this.material = materials[index];
  28579. return this;
  28580. }
  28581. }
  28582. // Multi
  28583. var multiMaterials = this.getScene().multiMaterials;
  28584. for (index = multiMaterials.length - 1; index > -1; index--) {
  28585. if (multiMaterials[index].id === id) {
  28586. this.material = multiMaterials[index];
  28587. return this;
  28588. }
  28589. }
  28590. return this;
  28591. };
  28592. /**
  28593. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28594. */
  28595. Mesh.prototype.getAnimatables = function () {
  28596. var results = new Array();
  28597. if (this.material) {
  28598. results.push(this.material);
  28599. }
  28600. if (this.skeleton) {
  28601. results.push(this.skeleton);
  28602. }
  28603. return results;
  28604. };
  28605. /**
  28606. * Modifies the mesh geometry according to the passed transformation matrix.
  28607. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28608. * The mesh normals are modified accordingly the same transformation.
  28609. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28610. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28611. * Returns the Mesh.
  28612. */
  28613. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28614. // Position
  28615. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28616. return this;
  28617. }
  28618. var submeshes = this.subMeshes.splice(0);
  28619. this._resetPointsArrayCache();
  28620. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28621. var temp = new Array();
  28622. var index;
  28623. for (index = 0; index < data.length; index += 3) {
  28624. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28625. }
  28626. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28627. // Normals
  28628. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28629. return this;
  28630. }
  28631. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28632. temp = [];
  28633. for (index = 0; index < data.length; index += 3) {
  28634. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28635. }
  28636. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28637. // flip faces?
  28638. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28639. this.flipFaces();
  28640. }
  28641. // Restore submeshes
  28642. this.releaseSubMeshes();
  28643. this.subMeshes = submeshes;
  28644. return this;
  28645. };
  28646. /**
  28647. * Modifies the mesh geometry according to its own current World Matrix.
  28648. * The mesh World Matrix is then reset.
  28649. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28650. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28651. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28652. * Returns the Mesh.
  28653. */
  28654. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28655. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28656. this.scaling.copyFromFloats(1, 1, 1);
  28657. this.position.copyFromFloats(0, 0, 0);
  28658. this.rotation.copyFromFloats(0, 0, 0);
  28659. //only if quaternion is already set
  28660. if (this.rotationQuaternion) {
  28661. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28662. }
  28663. this._worldMatrix = BABYLON.Matrix.Identity();
  28664. return this;
  28665. };
  28666. Object.defineProperty(Mesh.prototype, "_positions", {
  28667. // Cache
  28668. get: function () {
  28669. if (this._geometry) {
  28670. return this._geometry._positions;
  28671. }
  28672. return null;
  28673. },
  28674. enumerable: true,
  28675. configurable: true
  28676. });
  28677. Mesh.prototype._resetPointsArrayCache = function () {
  28678. if (this._geometry) {
  28679. this._geometry._resetPointsArrayCache();
  28680. }
  28681. return this;
  28682. };
  28683. Mesh.prototype._generatePointsArray = function () {
  28684. if (this._geometry) {
  28685. return this._geometry._generatePointsArray();
  28686. }
  28687. return false;
  28688. };
  28689. /**
  28690. * Returns a new Mesh object generated from the current mesh properties.
  28691. * This method must not get confused with createInstance().
  28692. * The parameter `name` is a string, the name given to the new mesh.
  28693. * The optional parameter `newParent` can be any Node object (default `null`).
  28694. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28695. * 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.
  28696. */
  28697. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28698. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28699. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28700. };
  28701. /**
  28702. * Disposes the Mesh.
  28703. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28704. * Returns nothing.
  28705. */
  28706. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28707. var _this = this;
  28708. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28709. this.morphTargetManager = null;
  28710. if (this._geometry) {
  28711. this._geometry.releaseForMesh(this, true);
  28712. }
  28713. // Sources
  28714. var meshes = this.getScene().meshes;
  28715. meshes.forEach(function (abstractMesh) {
  28716. var mesh = abstractMesh;
  28717. if (mesh._source && mesh._source === _this) {
  28718. mesh._source = null;
  28719. }
  28720. });
  28721. this._source = null;
  28722. // Instances
  28723. if (this._instancesBuffer) {
  28724. this._instancesBuffer.dispose();
  28725. this._instancesBuffer = null;
  28726. }
  28727. while (this.instances.length) {
  28728. this.instances[0].dispose();
  28729. }
  28730. // Effect layers.
  28731. var effectLayers = this.getScene().effectLayers;
  28732. for (var i = 0; i < effectLayers.length; i++) {
  28733. var effectLayer = effectLayers[i];
  28734. if (effectLayer) {
  28735. effectLayer._disposeMesh(this);
  28736. }
  28737. }
  28738. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28739. };
  28740. /**
  28741. * Modifies the mesh geometry according to a displacement map.
  28742. * 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.
  28743. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28744. * This method returns nothing.
  28745. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28746. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28747. * 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.
  28748. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28749. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28750. *
  28751. * Returns the Mesh.
  28752. */
  28753. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28754. var _this = this;
  28755. var scene = this.getScene();
  28756. var onload = function (img) {
  28757. // Getting height map data
  28758. var canvas = document.createElement("canvas");
  28759. var context = canvas.getContext("2d");
  28760. var heightMapWidth = img.width;
  28761. var heightMapHeight = img.height;
  28762. canvas.width = heightMapWidth;
  28763. canvas.height = heightMapHeight;
  28764. context.drawImage(img, 0, 0);
  28765. // Create VertexData from map data
  28766. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28767. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28768. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28769. //execute success callback, if set
  28770. if (onSuccess) {
  28771. onSuccess(_this);
  28772. }
  28773. };
  28774. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28775. return this;
  28776. };
  28777. /**
  28778. * Modifies the mesh geometry according to a displacementMap buffer.
  28779. * 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.
  28780. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28781. * This method returns nothing.
  28782. * 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.
  28783. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28784. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28785. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28786. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28787. *
  28788. * Returns the Mesh.
  28789. */
  28790. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28791. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28792. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28793. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28794. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28795. return this;
  28796. }
  28797. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28798. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28799. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28800. var position = BABYLON.Vector3.Zero();
  28801. var normal = BABYLON.Vector3.Zero();
  28802. var uv = BABYLON.Vector2.Zero();
  28803. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28804. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28805. for (var index = 0; index < positions.length; index += 3) {
  28806. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28807. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28808. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28809. // Compute height
  28810. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28811. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28812. var pos = (u + v * heightMapWidth) * 4;
  28813. var r = buffer[pos] / 255.0;
  28814. var g = buffer[pos + 1] / 255.0;
  28815. var b = buffer[pos + 2] / 255.0;
  28816. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28817. normal.normalize();
  28818. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28819. position = position.add(normal);
  28820. position.toArray(positions, index);
  28821. }
  28822. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28823. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28824. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28825. return this;
  28826. };
  28827. /**
  28828. * Modify the mesh to get a flat shading rendering.
  28829. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28830. * This method returns the Mesh.
  28831. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28832. */
  28833. Mesh.prototype.convertToFlatShadedMesh = function () {
  28834. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28835. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28836. var kinds = this.getVerticesDataKinds();
  28837. var vbs = {};
  28838. var data = {};
  28839. var newdata = {};
  28840. var updatableNormals = false;
  28841. var kindIndex;
  28842. var kind;
  28843. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28844. kind = kinds[kindIndex];
  28845. var vertexBuffer = this.getVertexBuffer(kind);
  28846. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28847. updatableNormals = vertexBuffer.isUpdatable();
  28848. kinds.splice(kindIndex, 1);
  28849. kindIndex--;
  28850. continue;
  28851. }
  28852. vbs[kind] = vertexBuffer;
  28853. data[kind] = vbs[kind].getData();
  28854. newdata[kind] = [];
  28855. }
  28856. // Save previous submeshes
  28857. var previousSubmeshes = this.subMeshes.slice(0);
  28858. var indices = this.getIndices();
  28859. var totalIndices = this.getTotalIndices();
  28860. // Generating unique vertices per face
  28861. var index;
  28862. for (index = 0; index < totalIndices; index++) {
  28863. var vertexIndex = indices[index];
  28864. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28865. kind = kinds[kindIndex];
  28866. var stride = vbs[kind].getStrideSize();
  28867. for (var offset = 0; offset < stride; offset++) {
  28868. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28869. }
  28870. }
  28871. }
  28872. // Updating faces & normal
  28873. var normals = [];
  28874. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28875. for (index = 0; index < totalIndices; index += 3) {
  28876. indices[index] = index;
  28877. indices[index + 1] = index + 1;
  28878. indices[index + 2] = index + 2;
  28879. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28880. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28881. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28882. var p1p2 = p1.subtract(p2);
  28883. var p3p2 = p3.subtract(p2);
  28884. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28885. // Store same normals for every vertex
  28886. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28887. normals.push(normal.x);
  28888. normals.push(normal.y);
  28889. normals.push(normal.z);
  28890. }
  28891. }
  28892. this.setIndices(indices);
  28893. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28894. // Updating vertex buffers
  28895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28896. kind = kinds[kindIndex];
  28897. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28898. }
  28899. // Updating submeshes
  28900. this.releaseSubMeshes();
  28901. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28902. var previousOne = previousSubmeshes[submeshIndex];
  28903. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28904. }
  28905. this.synchronizeInstances();
  28906. return this;
  28907. };
  28908. /**
  28909. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28910. * In other words, more vertices, no more indices and a single bigger VBO.
  28911. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28912. * Returns the Mesh.
  28913. */
  28914. Mesh.prototype.convertToUnIndexedMesh = function () {
  28915. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28916. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28917. var kinds = this.getVerticesDataKinds();
  28918. var vbs = {};
  28919. var data = {};
  28920. var newdata = {};
  28921. var kindIndex;
  28922. var kind;
  28923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28924. kind = kinds[kindIndex];
  28925. var vertexBuffer = this.getVertexBuffer(kind);
  28926. vbs[kind] = vertexBuffer;
  28927. data[kind] = vbs[kind].getData();
  28928. newdata[kind] = [];
  28929. }
  28930. // Save previous submeshes
  28931. var previousSubmeshes = this.subMeshes.slice(0);
  28932. var indices = this.getIndices();
  28933. var totalIndices = this.getTotalIndices();
  28934. // Generating unique vertices per face
  28935. var index;
  28936. for (index = 0; index < totalIndices; index++) {
  28937. var vertexIndex = indices[index];
  28938. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28939. kind = kinds[kindIndex];
  28940. var stride = vbs[kind].getStrideSize();
  28941. for (var offset = 0; offset < stride; offset++) {
  28942. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28943. }
  28944. }
  28945. }
  28946. // Updating indices
  28947. for (index = 0; index < totalIndices; index += 3) {
  28948. indices[index] = index;
  28949. indices[index + 1] = index + 1;
  28950. indices[index + 2] = index + 2;
  28951. }
  28952. this.setIndices(indices);
  28953. // Updating vertex buffers
  28954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28955. kind = kinds[kindIndex];
  28956. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28957. }
  28958. // Updating submeshes
  28959. this.releaseSubMeshes();
  28960. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28961. var previousOne = previousSubmeshes[submeshIndex];
  28962. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28963. }
  28964. this._unIndexed = true;
  28965. this.synchronizeInstances();
  28966. return this;
  28967. };
  28968. /**
  28969. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28970. * This method returns the Mesh.
  28971. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28972. */
  28973. Mesh.prototype.flipFaces = function (flipNormals) {
  28974. if (flipNormals === void 0) { flipNormals = false; }
  28975. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28976. var i;
  28977. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28978. for (i = 0; i < vertex_data.normals.length; i++) {
  28979. vertex_data.normals[i] *= -1;
  28980. }
  28981. }
  28982. if (vertex_data.indices) {
  28983. var temp;
  28984. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28985. // reassign indices
  28986. temp = vertex_data.indices[i + 1];
  28987. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28988. vertex_data.indices[i + 2] = temp;
  28989. }
  28990. }
  28991. vertex_data.applyToMesh(this);
  28992. return this;
  28993. };
  28994. // Instances
  28995. /**
  28996. * Creates a new InstancedMesh object from the mesh model.
  28997. * An instance shares the same properties and the same material than its model.
  28998. * Only these properties of each instance can then be set individually :
  28999. * - position
  29000. * - rotation
  29001. * - rotationQuaternion
  29002. * - setPivotMatrix
  29003. * - scaling
  29004. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29005. * Warning : this method is not supported for Line mesh and LineSystem
  29006. */
  29007. Mesh.prototype.createInstance = function (name) {
  29008. return new BABYLON.InstancedMesh(name, this);
  29009. };
  29010. /**
  29011. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29012. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29013. * This method returns the Mesh.
  29014. */
  29015. Mesh.prototype.synchronizeInstances = function () {
  29016. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29017. var instance = this.instances[instanceIndex];
  29018. instance._syncSubMeshes();
  29019. }
  29020. return this;
  29021. };
  29022. /**
  29023. * Simplify the mesh according to the given array of settings.
  29024. * Function will return immediately and will simplify async. It returns the Mesh.
  29025. * @param settings a collection of simplification settings.
  29026. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29027. * @param type the type of simplification to run.
  29028. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29029. */
  29030. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29031. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29032. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29033. this.getScene().simplificationQueue.addTask({
  29034. settings: settings,
  29035. parallelProcessing: parallelProcessing,
  29036. mesh: this,
  29037. simplificationType: simplificationType,
  29038. successCallback: successCallback
  29039. });
  29040. return this;
  29041. };
  29042. /**
  29043. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29044. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29045. * This should be used together with the simplification to avoid disappearing triangles.
  29046. * Returns the Mesh.
  29047. * @param successCallback an optional success callback to be called after the optimization finished.
  29048. */
  29049. Mesh.prototype.optimizeIndices = function (successCallback) {
  29050. var _this = this;
  29051. var indices = this.getIndices();
  29052. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29053. if (!positions || !indices) {
  29054. return this;
  29055. }
  29056. var vectorPositions = new Array();
  29057. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29058. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29059. }
  29060. var dupes = new Array();
  29061. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29062. var realPos = vectorPositions.length - 1 - iteration;
  29063. var testedPosition = vectorPositions[realPos];
  29064. for (var j = 0; j < realPos; ++j) {
  29065. var againstPosition = vectorPositions[j];
  29066. if (testedPosition.equals(againstPosition)) {
  29067. dupes[realPos] = j;
  29068. break;
  29069. }
  29070. }
  29071. }, function () {
  29072. for (var i = 0; i < indices.length; ++i) {
  29073. indices[i] = dupes[indices[i]] || indices[i];
  29074. }
  29075. //indices are now reordered
  29076. var originalSubMeshes = _this.subMeshes.slice(0);
  29077. _this.setIndices(indices);
  29078. _this.subMeshes = originalSubMeshes;
  29079. if (successCallback) {
  29080. successCallback(_this);
  29081. }
  29082. });
  29083. return this;
  29084. };
  29085. Mesh.prototype.serialize = function (serializationObject) {
  29086. serializationObject.name = this.name;
  29087. serializationObject.id = this.id;
  29088. serializationObject.type = this.getClassName();
  29089. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29090. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29091. }
  29092. serializationObject.position = this.position.asArray();
  29093. if (this.rotationQuaternion) {
  29094. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29095. }
  29096. else if (this.rotation) {
  29097. serializationObject.rotation = this.rotation.asArray();
  29098. }
  29099. serializationObject.scaling = this.scaling.asArray();
  29100. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29101. serializationObject.isEnabled = this.isEnabled(false);
  29102. serializationObject.isVisible = this.isVisible;
  29103. serializationObject.infiniteDistance = this.infiniteDistance;
  29104. serializationObject.pickable = this.isPickable;
  29105. serializationObject.receiveShadows = this.receiveShadows;
  29106. serializationObject.billboardMode = this.billboardMode;
  29107. serializationObject.visibility = this.visibility;
  29108. serializationObject.checkCollisions = this.checkCollisions;
  29109. serializationObject.isBlocker = this.isBlocker;
  29110. // Parent
  29111. if (this.parent) {
  29112. serializationObject.parentId = this.parent.id;
  29113. }
  29114. // Geometry
  29115. serializationObject.isUnIndexed = this.isUnIndexed;
  29116. var geometry = this._geometry;
  29117. if (geometry) {
  29118. var geometryId = geometry.id;
  29119. serializationObject.geometryId = geometryId;
  29120. // SubMeshes
  29121. serializationObject.subMeshes = [];
  29122. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29123. var subMesh = this.subMeshes[subIndex];
  29124. serializationObject.subMeshes.push({
  29125. materialIndex: subMesh.materialIndex,
  29126. verticesStart: subMesh.verticesStart,
  29127. verticesCount: subMesh.verticesCount,
  29128. indexStart: subMesh.indexStart,
  29129. indexCount: subMesh.indexCount
  29130. });
  29131. }
  29132. }
  29133. // Material
  29134. if (this.material) {
  29135. serializationObject.materialId = this.material.id;
  29136. }
  29137. else {
  29138. this.material = null;
  29139. }
  29140. // Morph targets
  29141. if (this.morphTargetManager) {
  29142. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29143. }
  29144. // Skeleton
  29145. if (this.skeleton) {
  29146. serializationObject.skeletonId = this.skeleton.id;
  29147. }
  29148. // Physics
  29149. //TODO implement correct serialization for physics impostors.
  29150. var impostor = this.getPhysicsImpostor();
  29151. if (impostor) {
  29152. serializationObject.physicsMass = impostor.getParam("mass");
  29153. serializationObject.physicsFriction = impostor.getParam("friction");
  29154. serializationObject.physicsRestitution = impostor.getParam("mass");
  29155. serializationObject.physicsImpostor = impostor.type;
  29156. }
  29157. // Metadata
  29158. if (this.metadata) {
  29159. serializationObject.metadata = this.metadata;
  29160. }
  29161. // Instances
  29162. serializationObject.instances = [];
  29163. for (var index = 0; index < this.instances.length; index++) {
  29164. var instance = this.instances[index];
  29165. var serializationInstance = {
  29166. name: instance.name,
  29167. id: instance.id,
  29168. position: instance.position.asArray(),
  29169. scaling: instance.scaling.asArray()
  29170. };
  29171. if (instance.rotationQuaternion) {
  29172. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29173. }
  29174. else if (instance.rotation) {
  29175. serializationInstance.rotation = instance.rotation.asArray();
  29176. }
  29177. serializationObject.instances.push(serializationInstance);
  29178. // Animations
  29179. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29180. serializationInstance.ranges = instance.serializeAnimationRanges();
  29181. }
  29182. //
  29183. // Animations
  29184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29185. serializationObject.ranges = this.serializeAnimationRanges();
  29186. // Layer mask
  29187. serializationObject.layerMask = this.layerMask;
  29188. // Alpha
  29189. serializationObject.alphaIndex = this.alphaIndex;
  29190. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29191. // Overlay
  29192. serializationObject.overlayAlpha = this.overlayAlpha;
  29193. serializationObject.overlayColor = this.overlayColor.asArray();
  29194. serializationObject.renderOverlay = this.renderOverlay;
  29195. // Fog
  29196. serializationObject.applyFog = this.applyFog;
  29197. // Action Manager
  29198. if (this.actionManager) {
  29199. serializationObject.actions = this.actionManager.serialize(this.name);
  29200. }
  29201. };
  29202. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29203. if (!this.geometry) {
  29204. return;
  29205. }
  29206. this._markSubMeshesAsAttributesDirty();
  29207. var morphTargetManager = this._morphTargetManager;
  29208. if (morphTargetManager && morphTargetManager.vertexCount) {
  29209. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29210. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29211. this.morphTargetManager = null;
  29212. return;
  29213. }
  29214. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29215. var morphTarget = morphTargetManager.getActiveTarget(index);
  29216. var positions = morphTarget.getPositions();
  29217. if (!positions) {
  29218. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29219. return;
  29220. }
  29221. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29222. var normals = morphTarget.getNormals();
  29223. if (normals) {
  29224. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29225. }
  29226. var tangents = morphTarget.getTangents();
  29227. if (tangents) {
  29228. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29229. }
  29230. }
  29231. }
  29232. else {
  29233. var index = 0;
  29234. // Positions
  29235. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29236. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29237. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29238. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29239. }
  29240. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29241. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29242. }
  29243. index++;
  29244. }
  29245. }
  29246. };
  29247. // Statics
  29248. /**
  29249. * Returns a new Mesh object parsed from the source provided.
  29250. * The parameter `parsedMesh` is the source.
  29251. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29252. */
  29253. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29254. var mesh;
  29255. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29256. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29257. }
  29258. else {
  29259. mesh = new Mesh(parsedMesh.name, scene);
  29260. }
  29261. mesh.id = parsedMesh.id;
  29262. if (BABYLON.Tags) {
  29263. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29264. }
  29265. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29266. if (parsedMesh.metadata !== undefined) {
  29267. mesh.metadata = parsedMesh.metadata;
  29268. }
  29269. if (parsedMesh.rotationQuaternion) {
  29270. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29271. }
  29272. else if (parsedMesh.rotation) {
  29273. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29274. }
  29275. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29276. if (parsedMesh.localMatrix) {
  29277. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29278. }
  29279. else if (parsedMesh.pivotMatrix) {
  29280. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29281. }
  29282. mesh.setEnabled(parsedMesh.isEnabled);
  29283. mesh.isVisible = parsedMesh.isVisible;
  29284. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29285. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29286. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29287. if (parsedMesh.applyFog !== undefined) {
  29288. mesh.applyFog = parsedMesh.applyFog;
  29289. }
  29290. if (parsedMesh.pickable !== undefined) {
  29291. mesh.isPickable = parsedMesh.pickable;
  29292. }
  29293. if (parsedMesh.alphaIndex !== undefined) {
  29294. mesh.alphaIndex = parsedMesh.alphaIndex;
  29295. }
  29296. mesh.receiveShadows = parsedMesh.receiveShadows;
  29297. mesh.billboardMode = parsedMesh.billboardMode;
  29298. if (parsedMesh.visibility !== undefined) {
  29299. mesh.visibility = parsedMesh.visibility;
  29300. }
  29301. mesh.checkCollisions = parsedMesh.checkCollisions;
  29302. if (parsedMesh.isBlocker !== undefined) {
  29303. mesh.isBlocker = parsedMesh.isBlocker;
  29304. }
  29305. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29306. // freezeWorldMatrix
  29307. if (parsedMesh.freezeWorldMatrix) {
  29308. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29309. }
  29310. // Parent
  29311. if (parsedMesh.parentId) {
  29312. mesh._waitingParentId = parsedMesh.parentId;
  29313. }
  29314. // Actions
  29315. if (parsedMesh.actions !== undefined) {
  29316. mesh._waitingActions = parsedMesh.actions;
  29317. }
  29318. // Overlay
  29319. if (parsedMesh.overlayAlpha !== undefined) {
  29320. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29321. }
  29322. if (parsedMesh.overlayColor !== undefined) {
  29323. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29324. }
  29325. if (parsedMesh.renderOverlay !== undefined) {
  29326. mesh.renderOverlay = parsedMesh.renderOverlay;
  29327. }
  29328. // Geometry
  29329. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29330. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29331. if (parsedMesh.delayLoadingFile) {
  29332. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29333. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29334. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29335. if (parsedMesh._binaryInfo) {
  29336. mesh._binaryInfo = parsedMesh._binaryInfo;
  29337. }
  29338. mesh._delayInfo = [];
  29339. if (parsedMesh.hasUVs) {
  29340. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29341. }
  29342. if (parsedMesh.hasUVs2) {
  29343. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29344. }
  29345. if (parsedMesh.hasUVs3) {
  29346. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29347. }
  29348. if (parsedMesh.hasUVs4) {
  29349. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29350. }
  29351. if (parsedMesh.hasUVs5) {
  29352. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29353. }
  29354. if (parsedMesh.hasUVs6) {
  29355. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29356. }
  29357. if (parsedMesh.hasColors) {
  29358. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29359. }
  29360. if (parsedMesh.hasMatricesIndices) {
  29361. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29362. }
  29363. if (parsedMesh.hasMatricesWeights) {
  29364. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29365. }
  29366. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29367. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29368. mesh._checkDelayState();
  29369. }
  29370. }
  29371. else {
  29372. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29373. }
  29374. // Material
  29375. if (parsedMesh.materialId) {
  29376. mesh.setMaterialByID(parsedMesh.materialId);
  29377. }
  29378. else {
  29379. mesh.material = null;
  29380. }
  29381. // Morph targets
  29382. if (parsedMesh.morphTargetManagerId > -1) {
  29383. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29384. }
  29385. // Skeleton
  29386. if (parsedMesh.skeletonId > -1) {
  29387. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29388. if (parsedMesh.numBoneInfluencers) {
  29389. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29390. }
  29391. }
  29392. // Animations
  29393. if (parsedMesh.animations) {
  29394. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29395. var parsedAnimation = parsedMesh.animations[animationIndex];
  29396. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29397. }
  29398. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29399. }
  29400. if (parsedMesh.autoAnimate) {
  29401. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29402. }
  29403. // Layer Mask
  29404. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29405. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29406. }
  29407. else {
  29408. mesh.layerMask = 0x0FFFFFFF;
  29409. }
  29410. // Physics
  29411. if (parsedMesh.physicsImpostor) {
  29412. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29413. mass: parsedMesh.physicsMass,
  29414. friction: parsedMesh.physicsFriction,
  29415. restitution: parsedMesh.physicsRestitution
  29416. }, scene);
  29417. }
  29418. // Instances
  29419. if (parsedMesh.instances) {
  29420. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29421. var parsedInstance = parsedMesh.instances[index];
  29422. var instance = mesh.createInstance(parsedInstance.name);
  29423. if (parsedInstance.id) {
  29424. instance.id = parsedInstance.id;
  29425. }
  29426. if (BABYLON.Tags) {
  29427. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29428. }
  29429. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29430. if (parsedInstance.parentId) {
  29431. instance._waitingParentId = parsedInstance.parentId;
  29432. }
  29433. if (parsedInstance.rotationQuaternion) {
  29434. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29435. }
  29436. else if (parsedInstance.rotation) {
  29437. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29438. }
  29439. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29440. instance.checkCollisions = mesh.checkCollisions;
  29441. if (parsedMesh.animations) {
  29442. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29443. parsedAnimation = parsedMesh.animations[animationIndex];
  29444. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29445. }
  29446. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29447. }
  29448. }
  29449. }
  29450. return mesh;
  29451. };
  29452. /**
  29453. * Creates a ribbon mesh.
  29454. * Please consider using the same method from the MeshBuilder class instead.
  29455. * 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.
  29456. *
  29457. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29458. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29459. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29460. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29461. * 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.
  29462. * 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.
  29463. * 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
  29464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29467. */
  29468. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29469. if (closeArray === void 0) { closeArray = false; }
  29470. if (updatable === void 0) { updatable = false; }
  29471. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29472. pathArray: pathArray,
  29473. closeArray: closeArray,
  29474. closePath: closePath,
  29475. offset: offset,
  29476. updatable: updatable,
  29477. sideOrientation: sideOrientation,
  29478. instance: instance
  29479. }, scene);
  29480. };
  29481. /**
  29482. * Creates a plane polygonal mesh. By default, this is a disc.
  29483. * Please consider using the same method from the MeshBuilder class instead.
  29484. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29485. * 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.
  29486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29489. */
  29490. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29491. if (scene === void 0) { scene = null; }
  29492. var options = {
  29493. radius: radius,
  29494. tessellation: tessellation,
  29495. sideOrientation: sideOrientation,
  29496. updatable: updatable
  29497. };
  29498. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29499. };
  29500. /**
  29501. * Creates a box mesh.
  29502. * Please consider using the same method from the MeshBuilder class instead.
  29503. * The parameter `size` sets the size (float) of each box side (default 1).
  29504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29507. */
  29508. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29509. if (scene === void 0) { scene = null; }
  29510. var options = {
  29511. size: size,
  29512. sideOrientation: sideOrientation,
  29513. updatable: updatable
  29514. };
  29515. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29516. };
  29517. /**
  29518. * Creates a sphere mesh.
  29519. * Please consider using the same method from the MeshBuilder class instead.
  29520. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29521. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29525. */
  29526. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29527. var options = {
  29528. segments: segments,
  29529. diameterX: diameter,
  29530. diameterY: diameter,
  29531. diameterZ: diameter,
  29532. sideOrientation: sideOrientation,
  29533. updatable: updatable
  29534. };
  29535. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29536. };
  29537. /**
  29538. * Creates a cylinder or a cone mesh.
  29539. * Please consider using the same method from the MeshBuilder class instead.
  29540. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29541. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29542. * 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.
  29543. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29544. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29545. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29548. */
  29549. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29550. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29551. if (scene !== undefined) {
  29552. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29553. updatable = scene;
  29554. }
  29555. scene = subdivisions;
  29556. subdivisions = 1;
  29557. }
  29558. var options = {
  29559. height: height,
  29560. diameterTop: diameterTop,
  29561. diameterBottom: diameterBottom,
  29562. tessellation: tessellation,
  29563. subdivisions: subdivisions,
  29564. sideOrientation: sideOrientation,
  29565. updatable: updatable
  29566. };
  29567. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29568. };
  29569. // Torus (Code from SharpDX.org)
  29570. /**
  29571. * Creates a torus mesh.
  29572. * Please consider using the same method from the MeshBuilder class instead.
  29573. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29574. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29575. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29579. */
  29580. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29581. var options = {
  29582. diameter: diameter,
  29583. thickness: thickness,
  29584. tessellation: tessellation,
  29585. sideOrientation: sideOrientation,
  29586. updatable: updatable
  29587. };
  29588. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29589. };
  29590. /**
  29591. * Creates a torus knot mesh.
  29592. * Please consider using the same method from the MeshBuilder class instead.
  29593. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29594. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29595. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29596. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29598. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29600. */
  29601. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29602. var options = {
  29603. radius: radius,
  29604. tube: tube,
  29605. radialSegments: radialSegments,
  29606. tubularSegments: tubularSegments,
  29607. p: p,
  29608. q: q,
  29609. sideOrientation: sideOrientation,
  29610. updatable: updatable
  29611. };
  29612. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29613. };
  29614. /**
  29615. * Creates a line mesh.
  29616. * Please consider using the same method from the MeshBuilder class instead.
  29617. * 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.
  29618. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29619. * The parameter `points` is an array successive Vector3.
  29620. * 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
  29621. * When updating an instance, remember that only point positions can change, not the number of points.
  29622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29623. */
  29624. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29625. if (scene === void 0) { scene = null; }
  29626. if (updatable === void 0) { updatable = false; }
  29627. if (instance === void 0) { instance = null; }
  29628. var options = {
  29629. points: points,
  29630. updatable: updatable,
  29631. instance: instance
  29632. };
  29633. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates a dashed line mesh.
  29637. * Please consider using the same method from the MeshBuilder class instead.
  29638. * 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.
  29639. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29640. * The parameter `points` is an array successive Vector3.
  29641. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29642. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29643. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29644. * 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
  29645. * When updating an instance, remember that only point positions can change, not the number of points.
  29646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29647. */
  29648. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29649. if (scene === void 0) { scene = null; }
  29650. var options = {
  29651. points: points,
  29652. dashSize: dashSize,
  29653. gapSize: gapSize,
  29654. dashNb: dashNb,
  29655. updatable: updatable,
  29656. instance: instance
  29657. };
  29658. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29659. };
  29660. /**
  29661. * Creates a polygon mesh.
  29662. * Please consider using the same method from the MeshBuilder class instead.
  29663. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29664. * 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.
  29665. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29667. * Remember you can only change the shape positions, not their number when updating a polygon.
  29668. */
  29669. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29670. var options = {
  29671. shape: shape,
  29672. holes: holes,
  29673. updatable: updatable,
  29674. sideOrientation: sideOrientation
  29675. };
  29676. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29677. };
  29678. /**
  29679. * Creates an extruded polygon mesh, with depth in the Y direction.
  29680. * Please consider using the same method from the MeshBuilder class instead.
  29681. */
  29682. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29683. var options = {
  29684. shape: shape,
  29685. holes: holes,
  29686. depth: depth,
  29687. updatable: updatable,
  29688. sideOrientation: sideOrientation
  29689. };
  29690. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29691. };
  29692. /**
  29693. * Creates an extruded shape mesh.
  29694. * 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.
  29695. * Please consider using the same method from the MeshBuilder class instead.
  29696. *
  29697. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29698. * 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
  29699. * extruded along the Z axis.
  29700. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29701. * 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.
  29702. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29703. * 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
  29704. * 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
  29705. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29709. */
  29710. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29711. if (scene === void 0) { scene = null; }
  29712. var options = {
  29713. shape: shape,
  29714. path: path,
  29715. scale: scale,
  29716. rotation: rotation,
  29717. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29718. sideOrientation: sideOrientation,
  29719. instance: instance,
  29720. updatable: updatable
  29721. };
  29722. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29723. };
  29724. /**
  29725. * Creates an custom extruded shape mesh.
  29726. * 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.
  29727. * Please consider using the same method from the MeshBuilder class instead.
  29728. *
  29729. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29730. * 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
  29731. * extruded along the Z axis.
  29732. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29733. * 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
  29734. * and the distance of this point from the begining of the path :
  29735. * ```javascript
  29736. * var rotationFunction = function(i, distance) {
  29737. * // do things
  29738. * return rotationValue; }
  29739. * ```
  29740. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29741. * 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
  29742. * and the distance of this point from the begining of the path :
  29743. * ```javascript
  29744. * var scaleFunction = function(i, distance) {
  29745. * // do things
  29746. * return scaleValue;}
  29747. * ```
  29748. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29749. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29750. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29751. * 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
  29752. * 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
  29753. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29757. */
  29758. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29759. var options = {
  29760. shape: shape,
  29761. path: path,
  29762. scaleFunction: scaleFunction,
  29763. rotationFunction: rotationFunction,
  29764. ribbonCloseArray: ribbonCloseArray,
  29765. ribbonClosePath: ribbonClosePath,
  29766. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29767. sideOrientation: sideOrientation,
  29768. instance: instance,
  29769. updatable: updatable
  29770. };
  29771. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29772. };
  29773. /**
  29774. * Creates lathe mesh.
  29775. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29776. * Please consider using the same method from the MeshBuilder class instead.
  29777. * 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
  29778. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29779. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29780. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29784. */
  29785. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29786. var options = {
  29787. shape: shape,
  29788. radius: radius,
  29789. tessellation: tessellation,
  29790. sideOrientation: sideOrientation,
  29791. updatable: updatable
  29792. };
  29793. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29794. };
  29795. /**
  29796. * Creates a plane mesh.
  29797. * Please consider using the same method from the MeshBuilder class instead.
  29798. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29799. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29800. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29801. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29802. */
  29803. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29804. var options = {
  29805. size: size,
  29806. width: size,
  29807. height: size,
  29808. sideOrientation: sideOrientation,
  29809. updatable: updatable
  29810. };
  29811. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29812. };
  29813. /**
  29814. * Creates a ground mesh.
  29815. * Please consider using the same method from the MeshBuilder class instead.
  29816. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29817. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29819. */
  29820. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29821. var options = {
  29822. width: width,
  29823. height: height,
  29824. subdivisions: subdivisions,
  29825. updatable: updatable
  29826. };
  29827. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29828. };
  29829. /**
  29830. * Creates a tiled ground mesh.
  29831. * Please consider using the same method from the MeshBuilder class instead.
  29832. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29833. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29834. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29835. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29836. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29837. * numbers of subdivisions on the ground width and height of each tile.
  29838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29839. */
  29840. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29841. var options = {
  29842. xmin: xmin,
  29843. zmin: zmin,
  29844. xmax: xmax,
  29845. zmax: zmax,
  29846. subdivisions: subdivisions,
  29847. precision: precision,
  29848. updatable: updatable
  29849. };
  29850. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29851. };
  29852. /**
  29853. * Creates a ground mesh from a height map.
  29854. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29855. * Please consider using the same method from the MeshBuilder class instead.
  29856. * The parameter `url` sets the URL of the height map image resource.
  29857. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29858. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29859. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29860. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29861. * 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).
  29862. * This function is passed the newly built mesh :
  29863. * ```javascript
  29864. * function(mesh) { // do things
  29865. * return; }
  29866. * ```
  29867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29868. */
  29869. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29870. var options = {
  29871. width: width,
  29872. height: height,
  29873. subdivisions: subdivisions,
  29874. minHeight: minHeight,
  29875. maxHeight: maxHeight,
  29876. updatable: updatable,
  29877. onReady: onReady
  29878. };
  29879. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29880. };
  29881. /**
  29882. * Creates a tube mesh.
  29883. * 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.
  29884. * Please consider using the same method from the MeshBuilder class instead.
  29885. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29886. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29887. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29888. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29889. * 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.
  29890. * It must return a radius value (positive float) :
  29891. * ```javascript
  29892. * var radiusFunction = function(i, distance) {
  29893. * // do things
  29894. * return radius; }
  29895. * ```
  29896. * 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
  29897. * 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
  29898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29899. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29901. */
  29902. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29903. var options = {
  29904. path: path,
  29905. radius: radius,
  29906. tessellation: tessellation,
  29907. radiusFunction: radiusFunction,
  29908. arc: 1,
  29909. cap: cap,
  29910. updatable: updatable,
  29911. sideOrientation: sideOrientation,
  29912. instance: instance
  29913. };
  29914. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29915. };
  29916. /**
  29917. * Creates a polyhedron mesh.
  29918. * Please consider using the same method from the MeshBuilder class instead.
  29919. * 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
  29920. * to choose the wanted type.
  29921. * The parameter `size` (positive float, default 1) sets the polygon size.
  29922. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29923. * 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`.
  29924. * 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
  29925. * 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)`).
  29926. * 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
  29927. * 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.
  29928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29929. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29931. */
  29932. Mesh.CreatePolyhedron = function (name, options, scene) {
  29933. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29934. };
  29935. /**
  29936. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29937. * Please consider using the same method from the MeshBuilder class instead.
  29938. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29939. * 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`).
  29940. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29941. * 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.
  29942. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29943. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29944. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29945. */
  29946. Mesh.CreateIcoSphere = function (name, options, scene) {
  29947. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29948. };
  29949. /**
  29950. * Creates a decal mesh.
  29951. * Please consider using the same method from the MeshBuilder class instead.
  29952. * 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.
  29953. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29954. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29955. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29956. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29957. */
  29958. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29959. var options = {
  29960. position: position,
  29961. normal: normal,
  29962. size: size,
  29963. angle: angle
  29964. };
  29965. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29966. };
  29967. // Skeletons
  29968. /**
  29969. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29970. */
  29971. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29972. if (!this._sourcePositions) {
  29973. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29974. if (!source) {
  29975. return this._sourcePositions;
  29976. }
  29977. this._sourcePositions = new Float32Array(source);
  29978. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29979. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29980. }
  29981. }
  29982. return this._sourcePositions;
  29983. };
  29984. /**
  29985. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29986. */
  29987. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29988. if (!this._sourceNormals) {
  29989. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29990. if (!source) {
  29991. return this._sourceNormals;
  29992. }
  29993. this._sourceNormals = new Float32Array(source);
  29994. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29995. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29996. }
  29997. }
  29998. return this._sourceNormals;
  29999. };
  30000. /**
  30001. * Updates the vertex buffer by applying transformation from the bones.
  30002. * Returns the Mesh.
  30003. *
  30004. * @param {skeleton} skeleton to apply
  30005. */
  30006. Mesh.prototype.applySkeleton = function (skeleton) {
  30007. if (!this.geometry) {
  30008. return this;
  30009. }
  30010. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30011. return this;
  30012. }
  30013. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30014. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30015. return this;
  30016. }
  30017. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30018. return this;
  30019. }
  30020. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30021. return this;
  30022. }
  30023. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30024. return this;
  30025. }
  30026. if (!this._sourcePositions) {
  30027. var submeshes = this.subMeshes.slice();
  30028. this.setPositionsForCPUSkinning();
  30029. this.subMeshes = submeshes;
  30030. }
  30031. if (!this._sourceNormals) {
  30032. this.setNormalsForCPUSkinning();
  30033. }
  30034. // positionsData checks for not being Float32Array will only pass at most once
  30035. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30036. if (!positionsData) {
  30037. return this;
  30038. }
  30039. if (!(positionsData instanceof Float32Array)) {
  30040. positionsData = new Float32Array(positionsData);
  30041. }
  30042. // normalsData checks for not being Float32Array will only pass at most once
  30043. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30044. if (!normalsData) {
  30045. return this;
  30046. }
  30047. if (!(normalsData instanceof Float32Array)) {
  30048. normalsData = new Float32Array(normalsData);
  30049. }
  30050. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30051. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30052. if (!matricesWeightsData || !matricesIndicesData) {
  30053. return this;
  30054. }
  30055. var needExtras = this.numBoneInfluencers > 4;
  30056. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30057. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30058. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30059. var tempVector3 = BABYLON.Vector3.Zero();
  30060. var finalMatrix = new BABYLON.Matrix();
  30061. var tempMatrix = new BABYLON.Matrix();
  30062. var matWeightIdx = 0;
  30063. var inf;
  30064. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30065. var weight;
  30066. for (inf = 0; inf < 4; inf++) {
  30067. weight = matricesWeightsData[matWeightIdx + inf];
  30068. if (weight > 0) {
  30069. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30070. finalMatrix.addToSelf(tempMatrix);
  30071. }
  30072. else
  30073. break;
  30074. }
  30075. if (needExtras) {
  30076. for (inf = 0; inf < 4; inf++) {
  30077. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30078. if (weight > 0) {
  30079. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30080. finalMatrix.addToSelf(tempMatrix);
  30081. }
  30082. else
  30083. break;
  30084. }
  30085. }
  30086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30087. tempVector3.toArray(positionsData, index);
  30088. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30089. tempVector3.toArray(normalsData, index);
  30090. finalMatrix.reset();
  30091. }
  30092. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30093. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30094. return this;
  30095. };
  30096. // Tools
  30097. /**
  30098. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30099. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30100. */
  30101. Mesh.MinMax = function (meshes) {
  30102. var minVector = null;
  30103. var maxVector = null;
  30104. meshes.forEach(function (mesh, index, array) {
  30105. var boundingInfo = mesh.getBoundingInfo();
  30106. var boundingBox = boundingInfo.boundingBox;
  30107. if (!minVector || !maxVector) {
  30108. minVector = boundingBox.minimumWorld;
  30109. maxVector = boundingBox.maximumWorld;
  30110. }
  30111. else {
  30112. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30113. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30114. }
  30115. });
  30116. if (!minVector || !maxVector) {
  30117. return {
  30118. min: BABYLON.Vector3.Zero(),
  30119. max: BABYLON.Vector3.Zero()
  30120. };
  30121. }
  30122. return {
  30123. min: minVector,
  30124. max: maxVector
  30125. };
  30126. };
  30127. /**
  30128. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30129. */
  30130. Mesh.Center = function (meshesOrMinMaxVector) {
  30131. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30132. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30133. };
  30134. /**
  30135. * Merge the array of meshes into a single mesh for performance reasons.
  30136. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30137. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30138. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30139. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30140. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30141. */
  30142. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30143. if (disposeSource === void 0) { disposeSource = true; }
  30144. var index;
  30145. if (!allow32BitsIndices) {
  30146. var totalVertices = 0;
  30147. // Counting vertices
  30148. for (index = 0; index < meshes.length; index++) {
  30149. if (meshes[index]) {
  30150. totalVertices += meshes[index].getTotalVertices();
  30151. if (totalVertices > 65536) {
  30152. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30153. return null;
  30154. }
  30155. }
  30156. }
  30157. }
  30158. // Merge
  30159. var vertexData = null;
  30160. var otherVertexData;
  30161. var indiceArray = new Array();
  30162. var source = null;
  30163. for (index = 0; index < meshes.length; index++) {
  30164. if (meshes[index]) {
  30165. meshes[index].computeWorldMatrix(true);
  30166. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30167. otherVertexData.transform(meshes[index].getWorldMatrix());
  30168. if (vertexData) {
  30169. vertexData.merge(otherVertexData);
  30170. }
  30171. else {
  30172. vertexData = otherVertexData;
  30173. source = meshes[index];
  30174. }
  30175. if (subdivideWithSubMeshes) {
  30176. indiceArray.push(meshes[index].getTotalIndices());
  30177. }
  30178. }
  30179. }
  30180. source = source;
  30181. if (!meshSubclass) {
  30182. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30183. }
  30184. vertexData.applyToMesh(meshSubclass);
  30185. // Setting properties
  30186. meshSubclass.material = source.material;
  30187. meshSubclass.checkCollisions = source.checkCollisions;
  30188. // Cleaning
  30189. if (disposeSource) {
  30190. for (index = 0; index < meshes.length; index++) {
  30191. if (meshes[index]) {
  30192. meshes[index].dispose();
  30193. }
  30194. }
  30195. }
  30196. // Subdivide
  30197. if (subdivideWithSubMeshes) {
  30198. //-- Suppresions du submesh global
  30199. meshSubclass.releaseSubMeshes();
  30200. index = 0;
  30201. var offset = 0;
  30202. //-- aplique la subdivision en fonction du tableau d'indices
  30203. while (index < indiceArray.length) {
  30204. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30205. offset += indiceArray[index];
  30206. index++;
  30207. }
  30208. }
  30209. return meshSubclass;
  30210. };
  30211. // Consts
  30212. Mesh._FRONTSIDE = 0;
  30213. Mesh._BACKSIDE = 1;
  30214. Mesh._DOUBLESIDE = 2;
  30215. Mesh._DEFAULTSIDE = 0;
  30216. Mesh._NO_CAP = 0;
  30217. Mesh._CAP_START = 1;
  30218. Mesh._CAP_END = 2;
  30219. Mesh._CAP_ALL = 3;
  30220. return Mesh;
  30221. }(BABYLON.AbstractMesh));
  30222. BABYLON.Mesh = Mesh;
  30223. })(BABYLON || (BABYLON = {}));
  30224. //# sourceMappingURL=babylon.mesh.js.map
  30225. var BABYLON;
  30226. (function (BABYLON) {
  30227. var BaseSubMesh = /** @class */ (function () {
  30228. function BaseSubMesh() {
  30229. }
  30230. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30231. get: function () {
  30232. return this._materialEffect;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30238. if (defines === void 0) { defines = null; }
  30239. if (this._materialEffect === effect) {
  30240. if (!effect) {
  30241. this._materialDefines = null;
  30242. }
  30243. return;
  30244. }
  30245. this._materialDefines = defines;
  30246. this._materialEffect = effect;
  30247. };
  30248. return BaseSubMesh;
  30249. }());
  30250. BABYLON.BaseSubMesh = BaseSubMesh;
  30251. var SubMesh = /** @class */ (function (_super) {
  30252. __extends(SubMesh, _super);
  30253. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30254. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30255. var _this = _super.call(this) || this;
  30256. _this.materialIndex = materialIndex;
  30257. _this.verticesStart = verticesStart;
  30258. _this.verticesCount = verticesCount;
  30259. _this.indexStart = indexStart;
  30260. _this.indexCount = indexCount;
  30261. _this._renderId = 0;
  30262. _this._mesh = mesh;
  30263. _this._renderingMesh = renderingMesh || mesh;
  30264. mesh.subMeshes.push(_this);
  30265. _this._trianglePlanes = [];
  30266. _this._id = mesh.subMeshes.length - 1;
  30267. if (createBoundingBox) {
  30268. _this.refreshBoundingInfo();
  30269. mesh.computeWorldMatrix(true);
  30270. }
  30271. return _this;
  30272. }
  30273. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30274. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30275. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30276. };
  30277. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30278. get: function () {
  30279. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. /**
  30285. * Returns the submesh BoudingInfo object.
  30286. */
  30287. SubMesh.prototype.getBoundingInfo = function () {
  30288. if (this.IsGlobal) {
  30289. return this._mesh.getBoundingInfo();
  30290. }
  30291. return this._boundingInfo;
  30292. };
  30293. /**
  30294. * Sets the submesh BoundingInfo.
  30295. * Return the SubMesh.
  30296. */
  30297. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30298. this._boundingInfo = boundingInfo;
  30299. return this;
  30300. };
  30301. /**
  30302. * Returns the mesh of the current submesh.
  30303. */
  30304. SubMesh.prototype.getMesh = function () {
  30305. return this._mesh;
  30306. };
  30307. /**
  30308. * Returns the rendering mesh of the submesh.
  30309. */
  30310. SubMesh.prototype.getRenderingMesh = function () {
  30311. return this._renderingMesh;
  30312. };
  30313. /**
  30314. * Returns the submesh material.
  30315. */
  30316. SubMesh.prototype.getMaterial = function () {
  30317. var rootMaterial = this._renderingMesh.material;
  30318. if (rootMaterial === null || rootMaterial === undefined) {
  30319. return this._mesh.getScene().defaultMaterial;
  30320. }
  30321. else if (rootMaterial.getSubMaterial) {
  30322. var multiMaterial = rootMaterial;
  30323. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30324. if (this._currentMaterial !== effectiveMaterial) {
  30325. this._currentMaterial = effectiveMaterial;
  30326. this._materialDefines = null;
  30327. }
  30328. return effectiveMaterial;
  30329. }
  30330. return rootMaterial;
  30331. };
  30332. // Methods
  30333. /**
  30334. * Sets a new updated BoundingInfo object to the submesh.
  30335. * Returns the SubMesh.
  30336. */
  30337. SubMesh.prototype.refreshBoundingInfo = function () {
  30338. this._lastColliderWorldVertices = null;
  30339. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30340. return this;
  30341. }
  30342. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30343. if (!data) {
  30344. this._boundingInfo = this._mesh.getBoundingInfo();
  30345. return this;
  30346. }
  30347. var indices = this._renderingMesh.getIndices();
  30348. var extend;
  30349. //is this the only submesh?
  30350. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30351. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30352. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30353. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30354. }
  30355. else {
  30356. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30357. }
  30358. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30359. return this;
  30360. };
  30361. SubMesh.prototype._checkCollision = function (collider) {
  30362. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30363. return boundingInfo._checkCollision(collider);
  30364. };
  30365. /**
  30366. * Updates the submesh BoundingInfo.
  30367. * Returns the Submesh.
  30368. */
  30369. SubMesh.prototype.updateBoundingInfo = function (world) {
  30370. var boundingInfo = this.getBoundingInfo();
  30371. if (!boundingInfo) {
  30372. this.refreshBoundingInfo();
  30373. boundingInfo = this.getBoundingInfo();
  30374. }
  30375. boundingInfo.update(world);
  30376. return this;
  30377. };
  30378. /**
  30379. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30380. * Boolean returned.
  30381. */
  30382. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30383. var boundingInfo = this.getBoundingInfo();
  30384. if (!boundingInfo) {
  30385. return false;
  30386. }
  30387. return boundingInfo.isInFrustum(frustumPlanes);
  30388. };
  30389. /**
  30390. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30391. * Boolean returned.
  30392. */
  30393. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30394. var boundingInfo = this.getBoundingInfo();
  30395. if (!boundingInfo) {
  30396. return false;
  30397. }
  30398. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30399. };
  30400. /**
  30401. * Renders the submesh.
  30402. * Returns it.
  30403. */
  30404. SubMesh.prototype.render = function (enableAlphaMode) {
  30405. this._renderingMesh.render(this, enableAlphaMode);
  30406. return this;
  30407. };
  30408. /**
  30409. * Returns a new Index Buffer.
  30410. * Type returned : WebGLBuffer.
  30411. */
  30412. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30413. if (!this._linesIndexBuffer) {
  30414. var linesIndices = [];
  30415. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30416. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30417. }
  30418. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30419. this.linesIndexCount = linesIndices.length;
  30420. }
  30421. return this._linesIndexBuffer;
  30422. };
  30423. /**
  30424. * True is the passed Ray intersects the submesh bounding box.
  30425. * Boolean returned.
  30426. */
  30427. SubMesh.prototype.canIntersects = function (ray) {
  30428. var boundingInfo = this.getBoundingInfo();
  30429. if (!boundingInfo) {
  30430. return false;
  30431. }
  30432. return ray.intersectsBox(boundingInfo.boundingBox);
  30433. };
  30434. /**
  30435. * Returns an object IntersectionInfo.
  30436. */
  30437. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30438. var intersectInfo = null;
  30439. // LineMesh first as it's also a Mesh...
  30440. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30441. var lineMesh = this._mesh;
  30442. // Line test
  30443. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30444. var p0 = positions[indices[index]];
  30445. var p1 = positions[indices[index + 1]];
  30446. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30447. if (length < 0) {
  30448. continue;
  30449. }
  30450. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30451. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30452. if (fastCheck) {
  30453. break;
  30454. }
  30455. }
  30456. }
  30457. }
  30458. else {
  30459. // Triangles test
  30460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30461. var p0 = positions[indices[index]];
  30462. var p1 = positions[indices[index + 1]];
  30463. var p2 = positions[indices[index + 2]];
  30464. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30465. if (currentIntersectInfo) {
  30466. if (currentIntersectInfo.distance < 0) {
  30467. continue;
  30468. }
  30469. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30470. intersectInfo = currentIntersectInfo;
  30471. intersectInfo.faceId = index / 3;
  30472. if (fastCheck) {
  30473. break;
  30474. }
  30475. }
  30476. }
  30477. }
  30478. }
  30479. return intersectInfo;
  30480. };
  30481. SubMesh.prototype._rebuild = function () {
  30482. if (this._linesIndexBuffer) {
  30483. this._linesIndexBuffer = null;
  30484. }
  30485. };
  30486. // Clone
  30487. /**
  30488. * Creates a new Submesh from the passed Mesh.
  30489. */
  30490. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30491. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30492. if (!this.IsGlobal) {
  30493. var boundingInfo = this.getBoundingInfo();
  30494. if (!boundingInfo) {
  30495. return result;
  30496. }
  30497. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30498. }
  30499. return result;
  30500. };
  30501. // Dispose
  30502. /**
  30503. * Disposes the Submesh.
  30504. * Returns nothing.
  30505. */
  30506. SubMesh.prototype.dispose = function () {
  30507. if (this._linesIndexBuffer) {
  30508. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30509. this._linesIndexBuffer = null;
  30510. }
  30511. // Remove from mesh
  30512. var index = this._mesh.subMeshes.indexOf(this);
  30513. this._mesh.subMeshes.splice(index, 1);
  30514. };
  30515. // Statics
  30516. /**
  30517. * Creates a new Submesh from the passed parameters :
  30518. * - materialIndex (integer) : the index of the main mesh material.
  30519. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30520. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30521. * - mesh (Mesh) : the main mesh to create the submesh from.
  30522. * - renderingMesh (optional Mesh) : rendering mesh.
  30523. */
  30524. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30525. var minVertexIndex = Number.MAX_VALUE;
  30526. var maxVertexIndex = -Number.MAX_VALUE;
  30527. renderingMesh = (renderingMesh || mesh);
  30528. var indices = renderingMesh.getIndices();
  30529. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30530. var vertexIndex = indices[index];
  30531. if (vertexIndex < minVertexIndex)
  30532. minVertexIndex = vertexIndex;
  30533. if (vertexIndex > maxVertexIndex)
  30534. maxVertexIndex = vertexIndex;
  30535. }
  30536. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30537. };
  30538. return SubMesh;
  30539. }(BaseSubMesh));
  30540. BABYLON.SubMesh = SubMesh;
  30541. })(BABYLON || (BABYLON = {}));
  30542. //# sourceMappingURL=babylon.subMesh.js.map
  30543. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30544. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30545. s = arguments[i];
  30546. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30547. t[p] = s[p];
  30548. }
  30549. return t;
  30550. };
  30551. var BABYLON;
  30552. (function (BABYLON) {
  30553. /**
  30554. * Manages the defines for the Material.
  30555. */
  30556. var MaterialDefines = /** @class */ (function () {
  30557. function MaterialDefines() {
  30558. this._isDirty = true;
  30559. this._areLightsDirty = true;
  30560. this._areAttributesDirty = true;
  30561. this._areTexturesDirty = true;
  30562. this._areFresnelDirty = true;
  30563. this._areMiscDirty = true;
  30564. this._areImageProcessingDirty = true;
  30565. this._normals = false;
  30566. this._uvs = false;
  30567. this._needNormals = false;
  30568. this._needUVs = false;
  30569. }
  30570. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30571. /**
  30572. * Specifies if the material needs to be re-calculated.
  30573. */
  30574. get: function () {
  30575. return this._isDirty;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. /**
  30581. * Marks the material to indicate that it has been re-calculated.
  30582. */
  30583. MaterialDefines.prototype.markAsProcessed = function () {
  30584. this._isDirty = false;
  30585. this._areAttributesDirty = false;
  30586. this._areTexturesDirty = false;
  30587. this._areFresnelDirty = false;
  30588. this._areLightsDirty = false;
  30589. this._areMiscDirty = false;
  30590. this._areImageProcessingDirty = false;
  30591. };
  30592. /**
  30593. * Marks the material to indicate that it needs to be re-calculated.
  30594. */
  30595. MaterialDefines.prototype.markAsUnprocessed = function () {
  30596. this._isDirty = true;
  30597. };
  30598. /**
  30599. * Marks the material to indicate all of its defines need to be re-calculated.
  30600. */
  30601. MaterialDefines.prototype.markAllAsDirty = function () {
  30602. this._areTexturesDirty = true;
  30603. this._areAttributesDirty = true;
  30604. this._areLightsDirty = true;
  30605. this._areFresnelDirty = true;
  30606. this._areMiscDirty = true;
  30607. this._areImageProcessingDirty = true;
  30608. this._isDirty = true;
  30609. };
  30610. /**
  30611. * Marks the material to indicate that image processing needs to be re-calculated.
  30612. */
  30613. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30614. this._areImageProcessingDirty = true;
  30615. this._isDirty = true;
  30616. };
  30617. /**
  30618. * Marks the material to indicate the lights need to be re-calculated.
  30619. */
  30620. MaterialDefines.prototype.markAsLightDirty = function () {
  30621. this._areLightsDirty = true;
  30622. this._isDirty = true;
  30623. };
  30624. /**
  30625. * Marks the attribute state as changed.
  30626. */
  30627. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30628. this._areAttributesDirty = true;
  30629. this._isDirty = true;
  30630. };
  30631. /**
  30632. * Marks the texture state as changed.
  30633. */
  30634. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30635. this._areTexturesDirty = true;
  30636. this._isDirty = true;
  30637. };
  30638. /**
  30639. * Marks the fresnel state as changed.
  30640. */
  30641. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30642. this._areFresnelDirty = true;
  30643. this._isDirty = true;
  30644. };
  30645. /**
  30646. * Marks the misc state as changed.
  30647. */
  30648. MaterialDefines.prototype.markAsMiscDirty = function () {
  30649. this._areMiscDirty = true;
  30650. this._isDirty = true;
  30651. };
  30652. /**
  30653. * Rebuilds the material defines.
  30654. */
  30655. MaterialDefines.prototype.rebuild = function () {
  30656. if (this._keys) {
  30657. delete this._keys;
  30658. }
  30659. this._keys = [];
  30660. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30661. var key = _a[_i];
  30662. if (key[0] === "_") {
  30663. continue;
  30664. }
  30665. this._keys.push(key);
  30666. }
  30667. };
  30668. /**
  30669. * Specifies if two material defines are equal.
  30670. * @param other - A material define instance to compare to.
  30671. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30672. */
  30673. MaterialDefines.prototype.isEqual = function (other) {
  30674. if (this._keys.length !== other._keys.length) {
  30675. return false;
  30676. }
  30677. for (var index = 0; index < this._keys.length; index++) {
  30678. var prop = this._keys[index];
  30679. if (this[prop] !== other[prop]) {
  30680. return false;
  30681. }
  30682. }
  30683. return true;
  30684. };
  30685. /**
  30686. * Clones this instance's defines to another instance.
  30687. * @param other - material defines to clone values to.
  30688. */
  30689. MaterialDefines.prototype.cloneTo = function (other) {
  30690. if (this._keys.length !== other._keys.length) {
  30691. other._keys = this._keys.slice(0);
  30692. }
  30693. for (var index = 0; index < this._keys.length; index++) {
  30694. var prop = this._keys[index];
  30695. other[prop] = this[prop];
  30696. }
  30697. };
  30698. /**
  30699. * Resets the material define values.
  30700. */
  30701. MaterialDefines.prototype.reset = function () {
  30702. for (var index = 0; index < this._keys.length; index++) {
  30703. var prop = this._keys[index];
  30704. if (typeof (this[prop]) === "number") {
  30705. this[prop] = 0;
  30706. }
  30707. else {
  30708. this[prop] = false;
  30709. }
  30710. }
  30711. };
  30712. /**
  30713. * Converts the material define values to a string.
  30714. * @returns - String of material define information.
  30715. */
  30716. MaterialDefines.prototype.toString = function () {
  30717. var result = "";
  30718. for (var index = 0; index < this._keys.length; index++) {
  30719. var prop = this._keys[index];
  30720. var value = this[prop];
  30721. if (typeof (value) === "number") {
  30722. result += "#define " + prop + " " + this[prop] + "\n";
  30723. }
  30724. else if (value) {
  30725. result += "#define " + prop + "\n";
  30726. }
  30727. }
  30728. return result;
  30729. };
  30730. return MaterialDefines;
  30731. }());
  30732. BABYLON.MaterialDefines = MaterialDefines;
  30733. /**
  30734. * This offers the main features of a material in BJS.
  30735. */
  30736. var Material = /** @class */ (function () {
  30737. /**
  30738. * Creates a material instance.
  30739. * @param name - The name of the material.
  30740. * @param scene - The BJS scene to reference.
  30741. * @param doNotAdd - Specifies if the material should be added to the scene.
  30742. */
  30743. function Material(name, scene, doNotAdd) {
  30744. /**
  30745. * Specifies if the ready state should be checked on each call.
  30746. */
  30747. this.checkReadyOnEveryCall = false;
  30748. /**
  30749. * Specifies if the ready state should be checked once.
  30750. */
  30751. this.checkReadyOnlyOnce = false;
  30752. /**
  30753. * The state of the material.
  30754. */
  30755. this.state = "";
  30756. /**
  30757. * The alpha value of the material.
  30758. */
  30759. this._alpha = 1.0;
  30760. /**
  30761. * Specifies if back face culling is enabled.
  30762. */
  30763. this._backFaceCulling = true;
  30764. /**
  30765. * Specifies if the material should be serialized.
  30766. */
  30767. this.doNotSerialize = false;
  30768. /**
  30769. * Specifies if the effect should be stored on sub meshes.
  30770. */
  30771. this.storeEffectOnSubMeshes = false;
  30772. /**
  30773. * An event triggered when the material is disposed.
  30774. * @type {BABYLON.Observable}
  30775. */
  30776. this.onDisposeObservable = new BABYLON.Observable();
  30777. /**
  30778. * An event triggered when the material is bound.
  30779. * @type {BABYLON.Observable}
  30780. */
  30781. this.onBindObservable = new BABYLON.Observable();
  30782. /**
  30783. * An event triggered when the material is unbound.
  30784. * @type {BABYLON.Observable}
  30785. */
  30786. this.onUnBindObservable = new BABYLON.Observable();
  30787. /**
  30788. * Stores the value of the alpha mode.
  30789. */
  30790. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30791. /**
  30792. * Stores the state of the need depth pre-pass value.
  30793. */
  30794. this._needDepthPrePass = false;
  30795. /**
  30796. * Specifies if depth writing should be disabled.
  30797. */
  30798. this.disableDepthWrite = false;
  30799. /**
  30800. * Specifies if depth writing should be forced.
  30801. */
  30802. this.forceDepthWrite = false;
  30803. /**
  30804. * Specifies if there should be a separate pass for culling.
  30805. */
  30806. this.separateCullingPass = false;
  30807. /**
  30808. * Stores the state specifing if fog should be enabled.
  30809. */
  30810. this._fogEnabled = true;
  30811. /**
  30812. * Stores the size of points.
  30813. */
  30814. this.pointSize = 1.0;
  30815. /**
  30816. * Stores the z offset value.
  30817. */
  30818. this.zOffset = 0;
  30819. /**
  30820. * Specifies if the material was previously ready.
  30821. */
  30822. this._wasPreviouslyReady = false;
  30823. /**
  30824. * Stores the fill mode state.
  30825. */
  30826. this._fillMode = Material.TriangleFillMode;
  30827. this.name = name;
  30828. this.id = name || BABYLON.Tools.RandomId();
  30829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30830. if (this._scene.useRightHandedSystem) {
  30831. this.sideOrientation = Material.ClockWiseSideOrientation;
  30832. }
  30833. else {
  30834. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30835. }
  30836. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30837. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30838. if (!doNotAdd) {
  30839. this._scene.materials.push(this);
  30840. }
  30841. }
  30842. Object.defineProperty(Material, "TriangleFillMode", {
  30843. /**
  30844. * Returns the triangle fill mode.
  30845. */
  30846. get: function () {
  30847. return Material._TriangleFillMode;
  30848. },
  30849. enumerable: true,
  30850. configurable: true
  30851. });
  30852. Object.defineProperty(Material, "WireFrameFillMode", {
  30853. /**
  30854. * Returns the wireframe mode.
  30855. */
  30856. get: function () {
  30857. return Material._WireFrameFillMode;
  30858. },
  30859. enumerable: true,
  30860. configurable: true
  30861. });
  30862. Object.defineProperty(Material, "PointFillMode", {
  30863. /**
  30864. * Returns the point fill mode.
  30865. */
  30866. get: function () {
  30867. return Material._PointFillMode;
  30868. },
  30869. enumerable: true,
  30870. configurable: true
  30871. });
  30872. Object.defineProperty(Material, "PointListDrawMode", {
  30873. /**
  30874. * Returns the point list draw mode.
  30875. */
  30876. get: function () {
  30877. return Material._PointListDrawMode;
  30878. },
  30879. enumerable: true,
  30880. configurable: true
  30881. });
  30882. Object.defineProperty(Material, "LineListDrawMode", {
  30883. /**
  30884. * Returns the line list draw mode.
  30885. */
  30886. get: function () {
  30887. return Material._LineListDrawMode;
  30888. },
  30889. enumerable: true,
  30890. configurable: true
  30891. });
  30892. Object.defineProperty(Material, "LineLoopDrawMode", {
  30893. /**
  30894. * Returns the line loop draw mode.
  30895. */
  30896. get: function () {
  30897. return Material._LineLoopDrawMode;
  30898. },
  30899. enumerable: true,
  30900. configurable: true
  30901. });
  30902. Object.defineProperty(Material, "LineStripDrawMode", {
  30903. /**
  30904. * Returns the line strip draw mode.
  30905. */
  30906. get: function () {
  30907. return Material._LineStripDrawMode;
  30908. },
  30909. enumerable: true,
  30910. configurable: true
  30911. });
  30912. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30913. /**
  30914. * Returns the triangle strip draw mode.
  30915. */
  30916. get: function () {
  30917. return Material._TriangleStripDrawMode;
  30918. },
  30919. enumerable: true,
  30920. configurable: true
  30921. });
  30922. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30923. /**
  30924. * Returns the triangle fan draw mode.
  30925. */
  30926. get: function () {
  30927. return Material._TriangleFanDrawMode;
  30928. },
  30929. enumerable: true,
  30930. configurable: true
  30931. });
  30932. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30933. /**
  30934. * Returns the clock-wise side orientation.
  30935. */
  30936. get: function () {
  30937. return Material._ClockWiseSideOrientation;
  30938. },
  30939. enumerable: true,
  30940. configurable: true
  30941. });
  30942. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30943. /**
  30944. * Returns the counter clock-wise side orientation.
  30945. */
  30946. get: function () {
  30947. return Material._CounterClockWiseSideOrientation;
  30948. },
  30949. enumerable: true,
  30950. configurable: true
  30951. });
  30952. Object.defineProperty(Material, "TextureDirtyFlag", {
  30953. /**
  30954. * Returns the dirty texture flag value.
  30955. */
  30956. get: function () {
  30957. return Material._TextureDirtyFlag;
  30958. },
  30959. enumerable: true,
  30960. configurable: true
  30961. });
  30962. Object.defineProperty(Material, "LightDirtyFlag", {
  30963. /**
  30964. * Returns the dirty light flag value.
  30965. */
  30966. get: function () {
  30967. return Material._LightDirtyFlag;
  30968. },
  30969. enumerable: true,
  30970. configurable: true
  30971. });
  30972. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30973. /**
  30974. * Returns the dirty fresnel flag value.
  30975. */
  30976. get: function () {
  30977. return Material._FresnelDirtyFlag;
  30978. },
  30979. enumerable: true,
  30980. configurable: true
  30981. });
  30982. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30983. /**
  30984. * Returns the dirty attributes flag value.
  30985. */
  30986. get: function () {
  30987. return Material._AttributesDirtyFlag;
  30988. },
  30989. enumerable: true,
  30990. configurable: true
  30991. });
  30992. Object.defineProperty(Material, "MiscDirtyFlag", {
  30993. /**
  30994. * Returns the dirty misc flag value.
  30995. */
  30996. get: function () {
  30997. return Material._MiscDirtyFlag;
  30998. },
  30999. enumerable: true,
  31000. configurable: true
  31001. });
  31002. Object.defineProperty(Material.prototype, "alpha", {
  31003. /**
  31004. * Gets the alpha value of the material.
  31005. */
  31006. get: function () {
  31007. return this._alpha;
  31008. },
  31009. /**
  31010. * Sets the alpha value of the material.
  31011. */
  31012. set: function (value) {
  31013. if (this._alpha === value) {
  31014. return;
  31015. }
  31016. this._alpha = value;
  31017. this.markAsDirty(Material.MiscDirtyFlag);
  31018. },
  31019. enumerable: true,
  31020. configurable: true
  31021. });
  31022. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31023. /**
  31024. * Gets the back-face culling state.
  31025. */
  31026. get: function () {
  31027. return this._backFaceCulling;
  31028. },
  31029. /**
  31030. * Sets the back-face culling state.
  31031. */
  31032. set: function (value) {
  31033. if (this._backFaceCulling === value) {
  31034. return;
  31035. }
  31036. this._backFaceCulling = value;
  31037. this.markAsDirty(Material.TextureDirtyFlag);
  31038. },
  31039. enumerable: true,
  31040. configurable: true
  31041. });
  31042. Object.defineProperty(Material.prototype, "onDispose", {
  31043. /**
  31044. * Called during a dispose event.
  31045. */
  31046. set: function (callback) {
  31047. if (this._onDisposeObserver) {
  31048. this.onDisposeObservable.remove(this._onDisposeObserver);
  31049. }
  31050. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Material.prototype, "onBind", {
  31056. /**
  31057. * Called during a bind event.
  31058. */
  31059. set: function (callback) {
  31060. if (this._onBindObserver) {
  31061. this.onBindObservable.remove(this._onBindObserver);
  31062. }
  31063. this._onBindObserver = this.onBindObservable.add(callback);
  31064. },
  31065. enumerable: true,
  31066. configurable: true
  31067. });
  31068. Object.defineProperty(Material.prototype, "alphaMode", {
  31069. /**
  31070. * Gets the value of the alpha mode.
  31071. */
  31072. get: function () {
  31073. return this._alphaMode;
  31074. },
  31075. /**
  31076. * Sets the value of the alpha mode.
  31077. */
  31078. set: function (value) {
  31079. if (this._alphaMode === value) {
  31080. return;
  31081. }
  31082. this._alphaMode = value;
  31083. this.markAsDirty(Material.TextureDirtyFlag);
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31089. /**
  31090. * Gets the depth pre-pass value.
  31091. */
  31092. get: function () {
  31093. return this._needDepthPrePass;
  31094. },
  31095. /**
  31096. * Sets the need depth pre-pass value.
  31097. */
  31098. set: function (value) {
  31099. if (this._needDepthPrePass === value) {
  31100. return;
  31101. }
  31102. this._needDepthPrePass = value;
  31103. if (this._needDepthPrePass) {
  31104. this.checkReadyOnEveryCall = true;
  31105. }
  31106. },
  31107. enumerable: true,
  31108. configurable: true
  31109. });
  31110. Object.defineProperty(Material.prototype, "fogEnabled", {
  31111. /**
  31112. * Gets the value of the fog enabled state.
  31113. */
  31114. get: function () {
  31115. return this._fogEnabled;
  31116. },
  31117. /**
  31118. * Sets the state for enabling fog.
  31119. */
  31120. set: function (value) {
  31121. if (this._fogEnabled === value) {
  31122. return;
  31123. }
  31124. this._fogEnabled = value;
  31125. this.markAsDirty(Material.MiscDirtyFlag);
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(Material.prototype, "wireframe", {
  31131. /**
  31132. * Gets a value specifying if wireframe mode is enabled.
  31133. */
  31134. get: function () {
  31135. return this._fillMode === Material.WireFrameFillMode;
  31136. },
  31137. /**
  31138. * Sets the state of wireframe mode.
  31139. */
  31140. set: function (value) {
  31141. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. Object.defineProperty(Material.prototype, "pointsCloud", {
  31147. /**
  31148. * Gets the value specifying if point clouds are enabled.
  31149. */
  31150. get: function () {
  31151. return this._fillMode === Material.PointFillMode;
  31152. },
  31153. /**
  31154. * Sets the state of point cloud mode.
  31155. */
  31156. set: function (value) {
  31157. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31158. },
  31159. enumerable: true,
  31160. configurable: true
  31161. });
  31162. Object.defineProperty(Material.prototype, "fillMode", {
  31163. /**
  31164. * Gets the material fill mode.
  31165. */
  31166. get: function () {
  31167. return this._fillMode;
  31168. },
  31169. /**
  31170. * Sets the material fill mode.
  31171. */
  31172. set: function (value) {
  31173. if (this._fillMode === value) {
  31174. return;
  31175. }
  31176. this._fillMode = value;
  31177. this.markAsDirty(Material.MiscDirtyFlag);
  31178. },
  31179. enumerable: true,
  31180. configurable: true
  31181. });
  31182. /**
  31183. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31184. * subclasses should override adding information pertainent to themselves.
  31185. * @returns - String with material information.
  31186. */
  31187. Material.prototype.toString = function (fullDetails) {
  31188. var ret = "Name: " + this.name;
  31189. if (fullDetails) {
  31190. }
  31191. return ret;
  31192. };
  31193. /**
  31194. * Gets the class name of the material.
  31195. * @returns - String with the class name of the material.
  31196. */
  31197. Material.prototype.getClassName = function () {
  31198. return "Material";
  31199. };
  31200. Object.defineProperty(Material.prototype, "isFrozen", {
  31201. /**
  31202. * Specifies if updates for the material been locked.
  31203. */
  31204. get: function () {
  31205. return this.checkReadyOnlyOnce;
  31206. },
  31207. enumerable: true,
  31208. configurable: true
  31209. });
  31210. /**
  31211. * Locks updates for the material.
  31212. */
  31213. Material.prototype.freeze = function () {
  31214. this.checkReadyOnlyOnce = true;
  31215. };
  31216. /**
  31217. * Unlocks updates for the material.
  31218. */
  31219. Material.prototype.unfreeze = function () {
  31220. this.checkReadyOnlyOnce = false;
  31221. };
  31222. /**
  31223. * Specifies if the material is ready to be used.
  31224. * @param mesh - BJS mesh.
  31225. * @param useInstances - Specifies if instances should be used.
  31226. * @returns - Boolean indicating if the material is ready to be used.
  31227. */
  31228. Material.prototype.isReady = function (mesh, useInstances) {
  31229. return true;
  31230. };
  31231. /**
  31232. * Specifies that the submesh is ready to be used.
  31233. * @param mesh - BJS mesh.
  31234. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31235. * @param useInstances - Specifies that instances should be used.
  31236. * @returns - boolean indicating that the submesh is ready or not.
  31237. */
  31238. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31239. return false;
  31240. };
  31241. /**
  31242. * Returns the material effect.
  31243. * @returns - Nullable material effect.
  31244. */
  31245. Material.prototype.getEffect = function () {
  31246. return this._effect;
  31247. };
  31248. /**
  31249. * Returns the BJS scene.
  31250. * @returns - BJS Scene.
  31251. */
  31252. Material.prototype.getScene = function () {
  31253. return this._scene;
  31254. };
  31255. /**
  31256. * Specifies if the material will require alpha blending
  31257. * @returns - Boolean specifying if alpha blending is needed.
  31258. */
  31259. Material.prototype.needAlphaBlending = function () {
  31260. return (this.alpha < 1.0);
  31261. };
  31262. /**
  31263. * Specifies if the mesh will require alpha blending.
  31264. * @param mesh - BJS mesh.
  31265. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31266. */
  31267. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31268. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31269. };
  31270. /**
  31271. * Specifies if this material should be rendered in alpha test mode.
  31272. * @returns - Boolean specifying if an alpha test is needed.
  31273. */
  31274. Material.prototype.needAlphaTesting = function () {
  31275. return false;
  31276. };
  31277. /**
  31278. * Gets the texture used for the alpha test.
  31279. * @returns - Nullable alpha test texture.
  31280. */
  31281. Material.prototype.getAlphaTestTexture = function () {
  31282. return null;
  31283. };
  31284. /**
  31285. * Marks the material to indicate that it needs to be re-calculated.
  31286. */
  31287. Material.prototype.markDirty = function () {
  31288. this._wasPreviouslyReady = false;
  31289. };
  31290. Material.prototype._preBind = function (effect, overrideOrientation) {
  31291. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31292. var engine = this._scene.getEngine();
  31293. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31294. var reverse = orientation === Material.ClockWiseSideOrientation;
  31295. engine.enableEffect(effect ? effect : this._effect);
  31296. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31297. return reverse;
  31298. };
  31299. /**
  31300. * Binds the material to the mesh.
  31301. * @param world - World transformation matrix.
  31302. * @param mesh - Mesh to bind the material to.
  31303. */
  31304. Material.prototype.bind = function (world, mesh) {
  31305. };
  31306. /**
  31307. * Binds the submesh to the material.
  31308. * @param world - World transformation matrix.
  31309. * @param mesh - Mesh containing the submesh.
  31310. * @param subMesh - Submesh to bind the material to.
  31311. */
  31312. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31313. };
  31314. /**
  31315. * Binds the world matrix to the material.
  31316. * @param world - World transformation matrix.
  31317. */
  31318. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31319. };
  31320. /**
  31321. * Binds the scene's uniform buffer to the effect.
  31322. * @param effect - Effect to bind to the scene uniform buffer.
  31323. * @param sceneUbo - Scene uniform buffer.
  31324. */
  31325. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31326. sceneUbo.bindToEffect(effect, "Scene");
  31327. };
  31328. /**
  31329. * Binds the view matrix to the effect.
  31330. * @param effect - Effect to bind the view matrix to.
  31331. */
  31332. Material.prototype.bindView = function (effect) {
  31333. if (!this._useUBO) {
  31334. effect.setMatrix("view", this.getScene().getViewMatrix());
  31335. }
  31336. else {
  31337. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31338. }
  31339. };
  31340. /**
  31341. * Binds the view projection matrix to the effect.
  31342. * @param effect - Effect to bind the view projection matrix to.
  31343. */
  31344. Material.prototype.bindViewProjection = function (effect) {
  31345. if (!this._useUBO) {
  31346. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31347. }
  31348. else {
  31349. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31350. }
  31351. };
  31352. /**
  31353. * Specifies if material alpha testing should be turned on for the mesh.
  31354. * @param mesh - BJS mesh.
  31355. */
  31356. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31357. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31358. };
  31359. /**
  31360. * Processes to execute after binding the material to a mesh.
  31361. * @param mesh - BJS mesh.
  31362. */
  31363. Material.prototype._afterBind = function (mesh) {
  31364. this._scene._cachedMaterial = this;
  31365. if (mesh) {
  31366. this._scene._cachedVisibility = mesh.visibility;
  31367. }
  31368. else {
  31369. this._scene._cachedVisibility = 1;
  31370. }
  31371. if (mesh) {
  31372. this.onBindObservable.notifyObservers(mesh);
  31373. }
  31374. if (this.disableDepthWrite) {
  31375. var engine = this._scene.getEngine();
  31376. this._cachedDepthWriteState = engine.getDepthWrite();
  31377. engine.setDepthWrite(false);
  31378. }
  31379. };
  31380. /**
  31381. * Unbinds the material from the mesh.
  31382. */
  31383. Material.prototype.unbind = function () {
  31384. this.onUnBindObservable.notifyObservers(this);
  31385. if (this.disableDepthWrite) {
  31386. var engine = this._scene.getEngine();
  31387. engine.setDepthWrite(this._cachedDepthWriteState);
  31388. }
  31389. };
  31390. /**
  31391. * Gets the active textures from the material.
  31392. * @returns - Array of textures.
  31393. */
  31394. Material.prototype.getActiveTextures = function () {
  31395. return [];
  31396. };
  31397. /**
  31398. * Specifies if the material uses a texture.
  31399. * @param texture - Texture to check against the material.
  31400. * @returns - Boolean specifying if the material uses the texture.
  31401. */
  31402. Material.prototype.hasTexture = function (texture) {
  31403. return false;
  31404. };
  31405. /**
  31406. * Makes a duplicate of the material, and gives it a new name.
  31407. * @param name - Name to call the duplicated material.
  31408. * @returns - Nullable cloned material
  31409. */
  31410. Material.prototype.clone = function (name) {
  31411. return null;
  31412. };
  31413. /**
  31414. * Gets the meshes bound to the material.
  31415. * @returns - Array of meshes bound to the material.
  31416. */
  31417. Material.prototype.getBindedMeshes = function () {
  31418. var result = new Array();
  31419. for (var index = 0; index < this._scene.meshes.length; index++) {
  31420. var mesh = this._scene.meshes[index];
  31421. if (mesh.material === this) {
  31422. result.push(mesh);
  31423. }
  31424. }
  31425. return result;
  31426. };
  31427. /**
  31428. * Force shader compilation
  31429. * @param mesh - BJS mesh.
  31430. * @param onCompiled - function to execute once the material is compiled.
  31431. * @param options - options to pass to this function.
  31432. */
  31433. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31434. var _this = this;
  31435. var localOptions = __assign({ clipPlane: false }, options);
  31436. var subMesh = new BABYLON.BaseSubMesh();
  31437. var scene = this.getScene();
  31438. var checkReady = function () {
  31439. if (!_this._scene || !_this._scene.getEngine()) {
  31440. return;
  31441. }
  31442. if (subMesh._materialDefines) {
  31443. subMesh._materialDefines._renderId = -1;
  31444. }
  31445. var clipPlaneState = scene.clipPlane;
  31446. if (localOptions.clipPlane) {
  31447. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31448. }
  31449. if (_this.storeEffectOnSubMeshes) {
  31450. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31451. if (onCompiled) {
  31452. onCompiled(_this);
  31453. }
  31454. }
  31455. else {
  31456. setTimeout(checkReady, 16);
  31457. }
  31458. }
  31459. else {
  31460. if (_this.isReady(mesh)) {
  31461. if (onCompiled) {
  31462. onCompiled(_this);
  31463. }
  31464. }
  31465. else {
  31466. setTimeout(checkReady, 16);
  31467. }
  31468. }
  31469. if (localOptions.clipPlane) {
  31470. scene.clipPlane = clipPlaneState;
  31471. }
  31472. };
  31473. checkReady();
  31474. };
  31475. /**
  31476. * Force shader compilation.
  31477. * @param mesh The mesh that will use this material
  31478. * @param options Additional options for compiling the shaders
  31479. * @returns A promise that resolves when the compilation completes
  31480. */
  31481. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31482. var _this = this;
  31483. return new Promise(function (resolve) {
  31484. _this.forceCompilation(mesh, function () {
  31485. resolve();
  31486. }, options);
  31487. });
  31488. };
  31489. /**
  31490. * Marks a define in the material to indicate that it needs to be re-computed.
  31491. * @param flag - Material define flag.
  31492. */
  31493. Material.prototype.markAsDirty = function (flag) {
  31494. if (flag & Material.TextureDirtyFlag) {
  31495. this._markAllSubMeshesAsTexturesDirty();
  31496. }
  31497. if (flag & Material.LightDirtyFlag) {
  31498. this._markAllSubMeshesAsLightsDirty();
  31499. }
  31500. if (flag & Material.FresnelDirtyFlag) {
  31501. this._markAllSubMeshesAsFresnelDirty();
  31502. }
  31503. if (flag & Material.AttributesDirtyFlag) {
  31504. this._markAllSubMeshesAsAttributesDirty();
  31505. }
  31506. if (flag & Material.MiscDirtyFlag) {
  31507. this._markAllSubMeshesAsMiscDirty();
  31508. }
  31509. this.getScene().resetCachedMaterial();
  31510. };
  31511. /**
  31512. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31513. * @param func - function which checks material defines against the submeshes.
  31514. */
  31515. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31516. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31517. var mesh = _a[_i];
  31518. if (!mesh.subMeshes) {
  31519. continue;
  31520. }
  31521. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31522. var subMesh = _c[_b];
  31523. if (subMesh.getMaterial() !== this) {
  31524. continue;
  31525. }
  31526. if (!subMesh._materialDefines) {
  31527. continue;
  31528. }
  31529. func(subMesh._materialDefines);
  31530. }
  31531. }
  31532. };
  31533. /**
  31534. * Indicates that image processing needs to be re-calculated for all submeshes.
  31535. */
  31536. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31537. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31538. };
  31539. /**
  31540. * Indicates that textures need to be re-calculated for all submeshes.
  31541. */
  31542. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31543. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31544. };
  31545. /**
  31546. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31547. */
  31548. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31549. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31550. };
  31551. /**
  31552. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31553. */
  31554. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31555. this._markAllSubMeshesAsDirty(function (defines) {
  31556. defines.markAsFresnelDirty();
  31557. defines.markAsMiscDirty();
  31558. });
  31559. };
  31560. /**
  31561. * Indicates that lights need to be re-calculated for all submeshes.
  31562. */
  31563. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31564. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31565. };
  31566. /**
  31567. * Indicates that attributes need to be re-calculated for all submeshes.
  31568. */
  31569. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31570. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31571. };
  31572. /**
  31573. * Indicates that misc needs to be re-calculated for all submeshes.
  31574. */
  31575. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31576. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31577. };
  31578. /**
  31579. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31580. */
  31581. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31582. this._markAllSubMeshesAsDirty(function (defines) {
  31583. defines.markAsTexturesDirty();
  31584. defines.markAsMiscDirty();
  31585. });
  31586. };
  31587. /**
  31588. * Disposes the material.
  31589. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31590. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31591. */
  31592. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31593. // Animations
  31594. this.getScene().stopAnimation(this);
  31595. // Remove from scene
  31596. var index = this._scene.materials.indexOf(this);
  31597. if (index >= 0) {
  31598. this._scene.materials.splice(index, 1);
  31599. }
  31600. // Remove from meshes
  31601. for (index = 0; index < this._scene.meshes.length; index++) {
  31602. var mesh = this._scene.meshes[index];
  31603. if (mesh.material === this) {
  31604. mesh.material = null;
  31605. if (mesh.geometry) {
  31606. var geometry = (mesh.geometry);
  31607. if (this.storeEffectOnSubMeshes) {
  31608. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31609. var subMesh = _a[_i];
  31610. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31611. if (forceDisposeEffect && subMesh._materialEffect) {
  31612. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31613. }
  31614. }
  31615. }
  31616. else {
  31617. geometry._releaseVertexArrayObject(this._effect);
  31618. }
  31619. }
  31620. }
  31621. }
  31622. this._uniformBuffer.dispose();
  31623. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31624. if (forceDisposeEffect && this._effect) {
  31625. if (!this.storeEffectOnSubMeshes) {
  31626. this._scene.getEngine()._releaseEffect(this._effect);
  31627. }
  31628. this._effect = null;
  31629. }
  31630. // Callback
  31631. this.onDisposeObservable.notifyObservers(this);
  31632. this.onDisposeObservable.clear();
  31633. this.onBindObservable.clear();
  31634. this.onUnBindObservable.clear();
  31635. };
  31636. /**
  31637. * Serializes this material.
  31638. * @returns - serialized material object.
  31639. */
  31640. Material.prototype.serialize = function () {
  31641. return BABYLON.SerializationHelper.Serialize(this);
  31642. };
  31643. /**
  31644. * Creates a MultiMaterial from parse MultiMaterial data.
  31645. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31646. * @param scene - BJS scene.
  31647. * @returns - MultiMaterial.
  31648. */
  31649. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31650. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31651. multiMaterial.id = parsedMultiMaterial.id;
  31652. if (BABYLON.Tags) {
  31653. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31654. }
  31655. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31656. var subMatId = parsedMultiMaterial.materials[matIndex];
  31657. if (subMatId) {
  31658. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31659. }
  31660. else {
  31661. multiMaterial.subMaterials.push(null);
  31662. }
  31663. }
  31664. return multiMaterial;
  31665. };
  31666. /**
  31667. * Creates a material from parsed material data.
  31668. * @param parsedMaterial - Parsed material data.
  31669. * @param scene - BJS scene.
  31670. * @param rootUrl - Root URL containing the material information.
  31671. * @returns - Parsed material.
  31672. */
  31673. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31674. if (!parsedMaterial.customType) {
  31675. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31676. }
  31677. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31678. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31679. if (!BABYLON.LegacyPBRMaterial) {
  31680. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31681. return;
  31682. }
  31683. }
  31684. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31685. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31686. ;
  31687. };
  31688. // Triangle views
  31689. Material._TriangleFillMode = 0;
  31690. Material._WireFrameFillMode = 1;
  31691. Material._PointFillMode = 2;
  31692. // Draw modes
  31693. Material._PointListDrawMode = 3;
  31694. Material._LineListDrawMode = 4;
  31695. Material._LineLoopDrawMode = 5;
  31696. Material._LineStripDrawMode = 6;
  31697. Material._TriangleStripDrawMode = 7;
  31698. Material._TriangleFanDrawMode = 8;
  31699. /**
  31700. * Stores the clock-wise side orientation.
  31701. */
  31702. Material._ClockWiseSideOrientation = 0;
  31703. /**
  31704. * Stores the counter clock-wise side orientation.
  31705. */
  31706. Material._CounterClockWiseSideOrientation = 1;
  31707. /**
  31708. * The dirty texture flag value.
  31709. */
  31710. Material._TextureDirtyFlag = 1;
  31711. /**
  31712. * The dirty light flag value.
  31713. */
  31714. Material._LightDirtyFlag = 2;
  31715. /**
  31716. * The dirty fresnel flag value.
  31717. */
  31718. Material._FresnelDirtyFlag = 4;
  31719. /**
  31720. * The dirty attribute flag value.
  31721. */
  31722. Material._AttributesDirtyFlag = 8;
  31723. /**
  31724. * The dirty misc flag value.
  31725. */
  31726. Material._MiscDirtyFlag = 16;
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], Material.prototype, "id", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], Material.prototype, "name", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31736. __decorate([
  31737. BABYLON.serialize()
  31738. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31739. __decorate([
  31740. BABYLON.serialize()
  31741. ], Material.prototype, "state", void 0);
  31742. __decorate([
  31743. BABYLON.serialize("alpha")
  31744. ], Material.prototype, "_alpha", void 0);
  31745. __decorate([
  31746. BABYLON.serialize("backFaceCulling")
  31747. ], Material.prototype, "_backFaceCulling", void 0);
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], Material.prototype, "sideOrientation", void 0);
  31751. __decorate([
  31752. BABYLON.serialize("alphaMode")
  31753. ], Material.prototype, "_alphaMode", void 0);
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], Material.prototype, "_needDepthPrePass", void 0);
  31757. __decorate([
  31758. BABYLON.serialize()
  31759. ], Material.prototype, "disableDepthWrite", void 0);
  31760. __decorate([
  31761. BABYLON.serialize()
  31762. ], Material.prototype, "forceDepthWrite", void 0);
  31763. __decorate([
  31764. BABYLON.serialize()
  31765. ], Material.prototype, "separateCullingPass", void 0);
  31766. __decorate([
  31767. BABYLON.serialize("fogEnabled")
  31768. ], Material.prototype, "_fogEnabled", void 0);
  31769. __decorate([
  31770. BABYLON.serialize()
  31771. ], Material.prototype, "pointSize", void 0);
  31772. __decorate([
  31773. BABYLON.serialize()
  31774. ], Material.prototype, "zOffset", void 0);
  31775. __decorate([
  31776. BABYLON.serialize()
  31777. ], Material.prototype, "wireframe", null);
  31778. __decorate([
  31779. BABYLON.serialize()
  31780. ], Material.prototype, "pointsCloud", null);
  31781. __decorate([
  31782. BABYLON.serialize()
  31783. ], Material.prototype, "fillMode", null);
  31784. return Material;
  31785. }());
  31786. BABYLON.Material = Material;
  31787. })(BABYLON || (BABYLON = {}));
  31788. //# sourceMappingURL=babylon.material.js.map
  31789. var BABYLON;
  31790. (function (BABYLON) {
  31791. var UniformBuffer = /** @class */ (function () {
  31792. /**
  31793. * Uniform buffer objects.
  31794. *
  31795. * Handles blocks of uniform on the GPU.
  31796. *
  31797. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31798. *
  31799. * For more information, please refer to :
  31800. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31801. */
  31802. function UniformBuffer(engine, data, dynamic) {
  31803. this._engine = engine;
  31804. this._noUBO = !engine.supportsUniformBuffers;
  31805. this._dynamic = dynamic;
  31806. this._data = data || [];
  31807. this._uniformLocations = {};
  31808. this._uniformSizes = {};
  31809. this._uniformLocationPointer = 0;
  31810. this._needSync = false;
  31811. if (this._noUBO) {
  31812. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31813. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31814. this.updateFloat = this._updateFloatForEffect;
  31815. this.updateFloat2 = this._updateFloat2ForEffect;
  31816. this.updateFloat3 = this._updateFloat3ForEffect;
  31817. this.updateFloat4 = this._updateFloat4ForEffect;
  31818. this.updateMatrix = this._updateMatrixForEffect;
  31819. this.updateVector3 = this._updateVector3ForEffect;
  31820. this.updateVector4 = this._updateVector4ForEffect;
  31821. this.updateColor3 = this._updateColor3ForEffect;
  31822. this.updateColor4 = this._updateColor4ForEffect;
  31823. }
  31824. else {
  31825. this._engine._uniformBuffers.push(this);
  31826. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31827. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31828. this.updateFloat = this._updateFloatForUniform;
  31829. this.updateFloat2 = this._updateFloat2ForUniform;
  31830. this.updateFloat3 = this._updateFloat3ForUniform;
  31831. this.updateFloat4 = this._updateFloat4ForUniform;
  31832. this.updateMatrix = this._updateMatrixForUniform;
  31833. this.updateVector3 = this._updateVector3ForUniform;
  31834. this.updateVector4 = this._updateVector4ForUniform;
  31835. this.updateColor3 = this._updateColor3ForUniform;
  31836. this.updateColor4 = this._updateColor4ForUniform;
  31837. }
  31838. }
  31839. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31840. // Properties
  31841. /**
  31842. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31843. * or just falling back on setUniformXXX calls.
  31844. */
  31845. get: function () {
  31846. return !this._noUBO;
  31847. },
  31848. enumerable: true,
  31849. configurable: true
  31850. });
  31851. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31852. /**
  31853. * Indicates if the WebGL underlying uniform buffer is in sync
  31854. * with the javascript cache data.
  31855. */
  31856. get: function () {
  31857. return !this._needSync;
  31858. },
  31859. enumerable: true,
  31860. configurable: true
  31861. });
  31862. /**
  31863. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31864. * Also, a dynamic UniformBuffer will disable cache verification and always
  31865. * update the underlying WebGL uniform buffer to the GPU.
  31866. */
  31867. UniformBuffer.prototype.isDynamic = function () {
  31868. return this._dynamic !== undefined;
  31869. };
  31870. /**
  31871. * The data cache on JS side.
  31872. */
  31873. UniformBuffer.prototype.getData = function () {
  31874. return this._bufferData;
  31875. };
  31876. /**
  31877. * The underlying WebGL Uniform buffer.
  31878. */
  31879. UniformBuffer.prototype.getBuffer = function () {
  31880. return this._buffer;
  31881. };
  31882. /**
  31883. * std140 layout specifies how to align data within an UBO structure.
  31884. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31885. * for specs.
  31886. */
  31887. UniformBuffer.prototype._fillAlignment = function (size) {
  31888. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31889. // and 4x4 matrices
  31890. // TODO : change if other types are used
  31891. var alignment;
  31892. if (size <= 2) {
  31893. alignment = size;
  31894. }
  31895. else {
  31896. alignment = 4;
  31897. }
  31898. if ((this._uniformLocationPointer % alignment) !== 0) {
  31899. var oldPointer = this._uniformLocationPointer;
  31900. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31901. var diff = this._uniformLocationPointer - oldPointer;
  31902. for (var i = 0; i < diff; i++) {
  31903. this._data.push(0);
  31904. }
  31905. }
  31906. };
  31907. /**
  31908. * Adds an uniform in the buffer.
  31909. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31910. * for the layout to be correct !
  31911. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31912. * @param {number|number[]} size Data size, or data directly.
  31913. */
  31914. UniformBuffer.prototype.addUniform = function (name, size) {
  31915. if (this._noUBO) {
  31916. return;
  31917. }
  31918. if (this._uniformLocations[name] !== undefined) {
  31919. // Already existing uniform
  31920. return;
  31921. }
  31922. // This function must be called in the order of the shader layout !
  31923. // size can be the size of the uniform, or data directly
  31924. var data;
  31925. if (size instanceof Array) {
  31926. data = size;
  31927. size = data.length;
  31928. }
  31929. else {
  31930. size = size;
  31931. data = [];
  31932. // Fill with zeros
  31933. for (var i = 0; i < size; i++) {
  31934. data.push(0);
  31935. }
  31936. }
  31937. this._fillAlignment(size);
  31938. this._uniformSizes[name] = size;
  31939. this._uniformLocations[name] = this._uniformLocationPointer;
  31940. this._uniformLocationPointer += size;
  31941. for (var i = 0; i < size; i++) {
  31942. this._data.push(data[i]);
  31943. }
  31944. this._needSync = true;
  31945. };
  31946. /**
  31947. * Wrapper for addUniform.
  31948. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31949. * @param {Matrix} mat A 4x4 matrix.
  31950. */
  31951. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31952. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31953. };
  31954. /**
  31955. * Wrapper for addUniform.
  31956. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31957. * @param {number} x
  31958. * @param {number} y
  31959. */
  31960. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31961. var temp = [x, y];
  31962. this.addUniform(name, temp);
  31963. };
  31964. /**
  31965. * Wrapper for addUniform.
  31966. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31967. * @param {number} x
  31968. * @param {number} y
  31969. * @param {number} z
  31970. */
  31971. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31972. var temp = [x, y, z];
  31973. this.addUniform(name, temp);
  31974. };
  31975. /**
  31976. * Wrapper for addUniform.
  31977. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31978. * @param {Color3} color
  31979. */
  31980. UniformBuffer.prototype.addColor3 = function (name, color) {
  31981. var temp = new Array();
  31982. color.toArray(temp);
  31983. this.addUniform(name, temp);
  31984. };
  31985. /**
  31986. * Wrapper for addUniform.
  31987. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31988. * @param {Color3} color
  31989. * @param {number} alpha
  31990. */
  31991. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31992. var temp = new Array();
  31993. color.toArray(temp);
  31994. temp.push(alpha);
  31995. this.addUniform(name, temp);
  31996. };
  31997. /**
  31998. * Wrapper for addUniform.
  31999. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32000. * @param {Vector3} vector
  32001. */
  32002. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32003. var temp = new Array();
  32004. vector.toArray(temp);
  32005. this.addUniform(name, temp);
  32006. };
  32007. /**
  32008. * Wrapper for addUniform.
  32009. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32010. */
  32011. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32012. this.addUniform(name, 12);
  32013. };
  32014. /**
  32015. * Wrapper for addUniform.
  32016. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32017. */
  32018. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32019. this.addUniform(name, 8);
  32020. };
  32021. /**
  32022. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32023. */
  32024. UniformBuffer.prototype.create = function () {
  32025. if (this._noUBO) {
  32026. return;
  32027. }
  32028. if (this._buffer) {
  32029. return; // nothing to do
  32030. }
  32031. // See spec, alignment must be filled as a vec4
  32032. this._fillAlignment(4);
  32033. this._bufferData = new Float32Array(this._data);
  32034. this._rebuild();
  32035. this._needSync = true;
  32036. };
  32037. UniformBuffer.prototype._rebuild = function () {
  32038. if (this._noUBO) {
  32039. return;
  32040. }
  32041. if (this._dynamic) {
  32042. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32043. }
  32044. else {
  32045. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32046. }
  32047. };
  32048. /**
  32049. * Updates the WebGL Uniform Buffer on the GPU.
  32050. * If the `dynamic` flag is set to true, no cache comparison is done.
  32051. * Otherwise, the buffer will be updated only if the cache differs.
  32052. */
  32053. UniformBuffer.prototype.update = function () {
  32054. if (!this._buffer) {
  32055. this.create();
  32056. return;
  32057. }
  32058. if (!this._dynamic && !this._needSync) {
  32059. return;
  32060. }
  32061. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32062. this._needSync = false;
  32063. };
  32064. /**
  32065. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32066. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32067. * @param {number[]|Float32Array} data Flattened data
  32068. * @param {number} size Size of the data.
  32069. */
  32070. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32071. var location = this._uniformLocations[uniformName];
  32072. if (location === undefined) {
  32073. if (this._buffer) {
  32074. // Cannot add an uniform if the buffer is already created
  32075. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32076. return;
  32077. }
  32078. this.addUniform(uniformName, size);
  32079. location = this._uniformLocations[uniformName];
  32080. }
  32081. if (!this._buffer) {
  32082. this.create();
  32083. }
  32084. if (!this._dynamic) {
  32085. // Cache for static uniform buffers
  32086. var changed = false;
  32087. for (var i = 0; i < size; i++) {
  32088. if (this._bufferData[location + i] !== data[i]) {
  32089. changed = true;
  32090. this._bufferData[location + i] = data[i];
  32091. }
  32092. }
  32093. this._needSync = this._needSync || changed;
  32094. }
  32095. else {
  32096. // No cache for dynamic
  32097. for (var i = 0; i < size; i++) {
  32098. this._bufferData[location + i] = data[i];
  32099. }
  32100. }
  32101. };
  32102. // Update methods
  32103. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32104. // To match std140, matrix must be realigned
  32105. for (var i = 0; i < 3; i++) {
  32106. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32107. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32108. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32109. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32110. }
  32111. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32112. };
  32113. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32114. this._currentEffect.setMatrix3x3(name, matrix);
  32115. };
  32116. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32117. this._currentEffect.setMatrix2x2(name, matrix);
  32118. };
  32119. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32120. // To match std140, matrix must be realigned
  32121. for (var i = 0; i < 2; i++) {
  32122. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32123. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32124. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32125. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32126. }
  32127. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32128. };
  32129. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32130. this._currentEffect.setFloat(name, x);
  32131. };
  32132. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32133. UniformBuffer._tempBuffer[0] = x;
  32134. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32135. };
  32136. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. this._currentEffect.setFloat2(name + suffix, x, y);
  32139. };
  32140. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32141. if (suffix === void 0) { suffix = ""; }
  32142. UniformBuffer._tempBuffer[0] = x;
  32143. UniformBuffer._tempBuffer[1] = y;
  32144. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32145. };
  32146. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32147. if (suffix === void 0) { suffix = ""; }
  32148. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32149. };
  32150. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32151. if (suffix === void 0) { suffix = ""; }
  32152. UniformBuffer._tempBuffer[0] = x;
  32153. UniformBuffer._tempBuffer[1] = y;
  32154. UniformBuffer._tempBuffer[2] = z;
  32155. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32156. };
  32157. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32158. if (suffix === void 0) { suffix = ""; }
  32159. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32160. };
  32161. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32162. if (suffix === void 0) { suffix = ""; }
  32163. UniformBuffer._tempBuffer[0] = x;
  32164. UniformBuffer._tempBuffer[1] = y;
  32165. UniformBuffer._tempBuffer[2] = z;
  32166. UniformBuffer._tempBuffer[3] = w;
  32167. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32168. };
  32169. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32170. this._currentEffect.setMatrix(name, mat);
  32171. };
  32172. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32173. this.updateUniform(name, mat.toArray(), 16);
  32174. };
  32175. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32176. this._currentEffect.setVector3(name, vector);
  32177. };
  32178. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32179. vector.toArray(UniformBuffer._tempBuffer);
  32180. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32181. };
  32182. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32183. this._currentEffect.setVector4(name, vector);
  32184. };
  32185. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32186. vector.toArray(UniformBuffer._tempBuffer);
  32187. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32188. };
  32189. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32190. if (suffix === void 0) { suffix = ""; }
  32191. this._currentEffect.setColor3(name + suffix, color);
  32192. };
  32193. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32194. if (suffix === void 0) { suffix = ""; }
  32195. color.toArray(UniformBuffer._tempBuffer);
  32196. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32197. };
  32198. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32199. if (suffix === void 0) { suffix = ""; }
  32200. this._currentEffect.setColor4(name + suffix, color, alpha);
  32201. };
  32202. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32203. if (suffix === void 0) { suffix = ""; }
  32204. color.toArray(UniformBuffer._tempBuffer);
  32205. UniformBuffer._tempBuffer[3] = alpha;
  32206. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32207. };
  32208. /**
  32209. * Sets a sampler uniform on the effect.
  32210. * @param {string} name Name of the sampler.
  32211. * @param {Texture} texture
  32212. */
  32213. UniformBuffer.prototype.setTexture = function (name, texture) {
  32214. this._currentEffect.setTexture(name, texture);
  32215. };
  32216. /**
  32217. * Directly updates the value of the uniform in the cache AND on the GPU.
  32218. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32219. * @param {number[]|Float32Array} data Flattened data
  32220. */
  32221. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32222. this.updateUniform(uniformName, data, data.length);
  32223. this.update();
  32224. };
  32225. /**
  32226. * Binds this uniform buffer to an effect.
  32227. * @param {Effect} effect
  32228. * @param {string} name Name of the uniform block in the shader.
  32229. */
  32230. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32231. this._currentEffect = effect;
  32232. if (this._noUBO || !this._buffer) {
  32233. return;
  32234. }
  32235. effect.bindUniformBuffer(this._buffer, name);
  32236. };
  32237. /**
  32238. * Disposes the uniform buffer.
  32239. */
  32240. UniformBuffer.prototype.dispose = function () {
  32241. if (this._noUBO) {
  32242. return;
  32243. }
  32244. var index = this._engine._uniformBuffers.indexOf(this);
  32245. if (index !== -1) {
  32246. this._engine._uniformBuffers.splice(index, 1);
  32247. }
  32248. if (!this._buffer) {
  32249. return;
  32250. }
  32251. if (this._engine._releaseBuffer(this._buffer)) {
  32252. this._buffer = null;
  32253. }
  32254. };
  32255. // Pool for avoiding memory leaks
  32256. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32257. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32258. return UniformBuffer;
  32259. }());
  32260. BABYLON.UniformBuffer = UniformBuffer;
  32261. })(BABYLON || (BABYLON = {}));
  32262. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32263. var BABYLON;
  32264. (function (BABYLON) {
  32265. var VertexData = /** @class */ (function () {
  32266. function VertexData() {
  32267. }
  32268. VertexData.prototype.set = function (data, kind) {
  32269. switch (kind) {
  32270. case BABYLON.VertexBuffer.PositionKind:
  32271. this.positions = data;
  32272. break;
  32273. case BABYLON.VertexBuffer.NormalKind:
  32274. this.normals = data;
  32275. break;
  32276. case BABYLON.VertexBuffer.TangentKind:
  32277. this.tangents = data;
  32278. break;
  32279. case BABYLON.VertexBuffer.UVKind:
  32280. this.uvs = data;
  32281. break;
  32282. case BABYLON.VertexBuffer.UV2Kind:
  32283. this.uvs2 = data;
  32284. break;
  32285. case BABYLON.VertexBuffer.UV3Kind:
  32286. this.uvs3 = data;
  32287. break;
  32288. case BABYLON.VertexBuffer.UV4Kind:
  32289. this.uvs4 = data;
  32290. break;
  32291. case BABYLON.VertexBuffer.UV5Kind:
  32292. this.uvs5 = data;
  32293. break;
  32294. case BABYLON.VertexBuffer.UV6Kind:
  32295. this.uvs6 = data;
  32296. break;
  32297. case BABYLON.VertexBuffer.ColorKind:
  32298. this.colors = data;
  32299. break;
  32300. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32301. this.matricesIndices = data;
  32302. break;
  32303. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32304. this.matricesWeights = data;
  32305. break;
  32306. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32307. this.matricesIndicesExtra = data;
  32308. break;
  32309. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32310. this.matricesWeightsExtra = data;
  32311. break;
  32312. }
  32313. };
  32314. /**
  32315. * Associates the vertexData to the passed Mesh.
  32316. * Sets it as updatable or not (default `false`).
  32317. * Returns the VertexData.
  32318. */
  32319. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32320. this._applyTo(mesh, updatable);
  32321. return this;
  32322. };
  32323. /**
  32324. * Associates the vertexData to the passed Geometry.
  32325. * Sets it as updatable or not (default `false`).
  32326. * Returns the VertexData.
  32327. */
  32328. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32329. this._applyTo(geometry, updatable);
  32330. return this;
  32331. };
  32332. /**
  32333. * Updates the associated mesh.
  32334. * Returns the VertexData.
  32335. */
  32336. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32337. this._update(mesh);
  32338. return this;
  32339. };
  32340. /**
  32341. * Updates the associated geometry.
  32342. * Returns the VertexData.
  32343. */
  32344. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32345. this._update(geometry);
  32346. return this;
  32347. };
  32348. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32349. if (updatable === void 0) { updatable = false; }
  32350. if (this.positions) {
  32351. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32352. }
  32353. if (this.normals) {
  32354. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32355. }
  32356. if (this.tangents) {
  32357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32358. }
  32359. if (this.uvs) {
  32360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32361. }
  32362. if (this.uvs2) {
  32363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32364. }
  32365. if (this.uvs3) {
  32366. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32367. }
  32368. if (this.uvs4) {
  32369. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32370. }
  32371. if (this.uvs5) {
  32372. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32373. }
  32374. if (this.uvs6) {
  32375. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32376. }
  32377. if (this.colors) {
  32378. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32379. }
  32380. if (this.matricesIndices) {
  32381. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32382. }
  32383. if (this.matricesWeights) {
  32384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32385. }
  32386. if (this.matricesIndicesExtra) {
  32387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32388. }
  32389. if (this.matricesWeightsExtra) {
  32390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32391. }
  32392. if (this.indices) {
  32393. meshOrGeometry.setIndices(this.indices, null, updatable);
  32394. }
  32395. return this;
  32396. };
  32397. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32398. if (this.positions) {
  32399. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32400. }
  32401. if (this.normals) {
  32402. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32403. }
  32404. if (this.tangents) {
  32405. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32406. }
  32407. if (this.uvs) {
  32408. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32409. }
  32410. if (this.uvs2) {
  32411. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32412. }
  32413. if (this.uvs3) {
  32414. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32415. }
  32416. if (this.uvs4) {
  32417. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32418. }
  32419. if (this.uvs5) {
  32420. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32421. }
  32422. if (this.uvs6) {
  32423. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32424. }
  32425. if (this.colors) {
  32426. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32427. }
  32428. if (this.matricesIndices) {
  32429. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32430. }
  32431. if (this.matricesWeights) {
  32432. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32433. }
  32434. if (this.matricesIndicesExtra) {
  32435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32436. }
  32437. if (this.matricesWeightsExtra) {
  32438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32439. }
  32440. if (this.indices) {
  32441. meshOrGeometry.setIndices(this.indices, null);
  32442. }
  32443. return this;
  32444. };
  32445. /**
  32446. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32447. * Returns the VertexData.
  32448. */
  32449. VertexData.prototype.transform = function (matrix) {
  32450. var transformed = BABYLON.Vector3.Zero();
  32451. var index;
  32452. if (this.positions) {
  32453. var position = BABYLON.Vector3.Zero();
  32454. for (index = 0; index < this.positions.length; index += 3) {
  32455. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32456. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32457. this.positions[index] = transformed.x;
  32458. this.positions[index + 1] = transformed.y;
  32459. this.positions[index + 2] = transformed.z;
  32460. }
  32461. }
  32462. if (this.normals) {
  32463. var normal = BABYLON.Vector3.Zero();
  32464. for (index = 0; index < this.normals.length; index += 3) {
  32465. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32466. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32467. this.normals[index] = transformed.x;
  32468. this.normals[index + 1] = transformed.y;
  32469. this.normals[index + 2] = transformed.z;
  32470. }
  32471. }
  32472. if (this.tangents) {
  32473. var tangent = BABYLON.Vector4.Zero();
  32474. var tangentTransformed = BABYLON.Vector4.Zero();
  32475. for (index = 0; index < this.tangents.length; index += 4) {
  32476. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32477. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32478. this.tangents[index] = tangentTransformed.x;
  32479. this.tangents[index + 1] = tangentTransformed.y;
  32480. this.tangents[index + 2] = tangentTransformed.z;
  32481. this.tangents[index + 3] = tangentTransformed.w;
  32482. }
  32483. }
  32484. return this;
  32485. };
  32486. /**
  32487. * Merges the passed VertexData into the current one.
  32488. * Returns the modified VertexData.
  32489. */
  32490. VertexData.prototype.merge = function (other) {
  32491. this._validate();
  32492. other._validate();
  32493. if (!this.normals !== !other.normals ||
  32494. !this.tangents !== !other.tangents ||
  32495. !this.uvs !== !other.uvs ||
  32496. !this.uvs2 !== !other.uvs2 ||
  32497. !this.uvs3 !== !other.uvs3 ||
  32498. !this.uvs4 !== !other.uvs4 ||
  32499. !this.uvs5 !== !other.uvs5 ||
  32500. !this.uvs6 !== !other.uvs6 ||
  32501. !this.colors !== !other.colors ||
  32502. !this.matricesIndices !== !other.matricesIndices ||
  32503. !this.matricesWeights !== !other.matricesWeights ||
  32504. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32505. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32506. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32507. }
  32508. if (other.indices) {
  32509. if (!this.indices) {
  32510. this.indices = [];
  32511. }
  32512. var offset = this.positions ? this.positions.length / 3 : 0;
  32513. for (var index = 0; index < other.indices.length; index++) {
  32514. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32515. this.indices.push(other.indices[index] + offset);
  32516. }
  32517. }
  32518. this.positions = this._mergeElement(this.positions, other.positions);
  32519. this.normals = this._mergeElement(this.normals, other.normals);
  32520. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32521. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32522. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32523. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32524. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32525. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32526. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32527. this.colors = this._mergeElement(this.colors, other.colors);
  32528. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32529. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32530. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32531. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32532. return this;
  32533. };
  32534. VertexData.prototype._mergeElement = function (source, other) {
  32535. if (!source) {
  32536. return other;
  32537. }
  32538. if (!other) {
  32539. return source;
  32540. }
  32541. var len = other.length + source.length;
  32542. var isSrcTypedArray = source instanceof Float32Array;
  32543. var isOthTypedArray = other instanceof Float32Array;
  32544. // use non-loop method when the source is Float32Array
  32545. if (isSrcTypedArray) {
  32546. var ret32 = new Float32Array(len);
  32547. ret32.set(source);
  32548. ret32.set(other, source.length);
  32549. return ret32;
  32550. // source is number[], when other is also use concat
  32551. }
  32552. else if (!isOthTypedArray) {
  32553. return source.concat(other);
  32554. // source is a number[], but other is a Float32Array, loop required
  32555. }
  32556. else {
  32557. var ret = source.slice(0); // copy source to a separate array
  32558. for (var i = 0, len = other.length; i < len; i++) {
  32559. ret.push(other[i]);
  32560. }
  32561. return ret;
  32562. }
  32563. };
  32564. VertexData.prototype._validate = function () {
  32565. if (!this.positions) {
  32566. throw new Error("Positions are required");
  32567. }
  32568. var getElementCount = function (kind, values) {
  32569. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32570. if ((values.length % stride) !== 0) {
  32571. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32572. }
  32573. return values.length / stride;
  32574. };
  32575. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32576. var validateElementCount = function (kind, values) {
  32577. var elementCount = getElementCount(kind, values);
  32578. if (elementCount !== positionsElementCount) {
  32579. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32580. }
  32581. };
  32582. if (this.normals)
  32583. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32584. if (this.tangents)
  32585. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32586. if (this.uvs)
  32587. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32588. if (this.uvs2)
  32589. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32590. if (this.uvs3)
  32591. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32592. if (this.uvs4)
  32593. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32594. if (this.uvs5)
  32595. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32596. if (this.uvs6)
  32597. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32598. if (this.colors)
  32599. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32600. if (this.matricesIndices)
  32601. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32602. if (this.matricesWeights)
  32603. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32604. if (this.matricesIndicesExtra)
  32605. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32606. if (this.matricesWeightsExtra)
  32607. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32608. };
  32609. /**
  32610. * Serializes the VertexData.
  32611. * Returns a serialized object.
  32612. */
  32613. VertexData.prototype.serialize = function () {
  32614. var serializationObject = this.serialize();
  32615. if (this.positions) {
  32616. serializationObject.positions = this.positions;
  32617. }
  32618. if (this.normals) {
  32619. serializationObject.normals = this.normals;
  32620. }
  32621. if (this.tangents) {
  32622. serializationObject.tangents = this.tangents;
  32623. }
  32624. if (this.uvs) {
  32625. serializationObject.uvs = this.uvs;
  32626. }
  32627. if (this.uvs2) {
  32628. serializationObject.uvs2 = this.uvs2;
  32629. }
  32630. if (this.uvs3) {
  32631. serializationObject.uvs3 = this.uvs3;
  32632. }
  32633. if (this.uvs4) {
  32634. serializationObject.uvs4 = this.uvs4;
  32635. }
  32636. if (this.uvs5) {
  32637. serializationObject.uvs5 = this.uvs5;
  32638. }
  32639. if (this.uvs6) {
  32640. serializationObject.uvs6 = this.uvs6;
  32641. }
  32642. if (this.colors) {
  32643. serializationObject.colors = this.colors;
  32644. }
  32645. if (this.matricesIndices) {
  32646. serializationObject.matricesIndices = this.matricesIndices;
  32647. serializationObject.matricesIndices._isExpanded = true;
  32648. }
  32649. if (this.matricesWeights) {
  32650. serializationObject.matricesWeights = this.matricesWeights;
  32651. }
  32652. if (this.matricesIndicesExtra) {
  32653. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32654. serializationObject.matricesIndicesExtra._isExpanded = true;
  32655. }
  32656. if (this.matricesWeightsExtra) {
  32657. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32658. }
  32659. serializationObject.indices = this.indices;
  32660. return serializationObject;
  32661. };
  32662. // Statics
  32663. /**
  32664. * Returns the object VertexData associated to the passed mesh.
  32665. */
  32666. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32667. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32668. };
  32669. /**
  32670. * Returns the object VertexData associated to the passed geometry.
  32671. */
  32672. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32673. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32674. };
  32675. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32676. var result = new VertexData();
  32677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32678. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32679. }
  32680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32681. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32682. }
  32683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32684. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32685. }
  32686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32687. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32688. }
  32689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32690. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32691. }
  32692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32693. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32694. }
  32695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32696. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32697. }
  32698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32699. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32700. }
  32701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32702. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32703. }
  32704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32705. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32706. }
  32707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32708. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32709. }
  32710. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32711. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32712. }
  32713. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32714. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32715. }
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32717. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32718. }
  32719. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32720. return result;
  32721. };
  32722. /**
  32723. * Creates the vertexData of the Ribbon.
  32724. */
  32725. VertexData.CreateRibbon = function (options) {
  32726. var pathArray = options.pathArray;
  32727. var closeArray = options.closeArray || false;
  32728. var closePath = options.closePath || false;
  32729. var invertUV = options.invertUV || false;
  32730. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32731. var offset = options.offset || defaultOffset;
  32732. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32734. var customUV = options.uvs;
  32735. var customColors = options.colors;
  32736. var positions = [];
  32737. var indices = [];
  32738. var normals = [];
  32739. var uvs = [];
  32740. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32741. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32742. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32743. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32744. var minlg; // minimal length among all paths from pathArray
  32745. var lg = []; // array of path lengths : nb of vertex per path
  32746. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32747. var p; // path iterator
  32748. var i; // point iterator
  32749. var j; // point iterator
  32750. // if single path in pathArray
  32751. if (pathArray.length < 2) {
  32752. var ar1 = [];
  32753. var ar2 = [];
  32754. for (i = 0; i < pathArray[0].length - offset; i++) {
  32755. ar1.push(pathArray[0][i]);
  32756. ar2.push(pathArray[0][i + offset]);
  32757. }
  32758. pathArray = [ar1, ar2];
  32759. }
  32760. // positions and horizontal distances (u)
  32761. var idc = 0;
  32762. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32763. var path;
  32764. var l;
  32765. minlg = pathArray[0].length;
  32766. var vectlg;
  32767. var dist;
  32768. for (p = 0; p < pathArray.length; p++) {
  32769. uTotalDistance[p] = 0;
  32770. us[p] = [0];
  32771. path = pathArray[p];
  32772. l = path.length;
  32773. minlg = (minlg < l) ? minlg : l;
  32774. j = 0;
  32775. while (j < l) {
  32776. positions.push(path[j].x, path[j].y, path[j].z);
  32777. if (j > 0) {
  32778. vectlg = path[j].subtract(path[j - 1]).length();
  32779. dist = vectlg + uTotalDistance[p];
  32780. us[p].push(dist);
  32781. uTotalDistance[p] = dist;
  32782. }
  32783. j++;
  32784. }
  32785. if (closePath) {
  32786. j--;
  32787. positions.push(path[0].x, path[0].y, path[0].z);
  32788. vectlg = path[j].subtract(path[0]).length();
  32789. dist = vectlg + uTotalDistance[p];
  32790. us[p].push(dist);
  32791. uTotalDistance[p] = dist;
  32792. }
  32793. lg[p] = l + closePathCorr;
  32794. idx[p] = idc;
  32795. idc += (l + closePathCorr);
  32796. }
  32797. // vertical distances (v)
  32798. var path1;
  32799. var path2;
  32800. var vertex1 = null;
  32801. var vertex2 = null;
  32802. for (i = 0; i < minlg + closePathCorr; i++) {
  32803. vTotalDistance[i] = 0;
  32804. vs[i] = [0];
  32805. for (p = 0; p < pathArray.length - 1; p++) {
  32806. path1 = pathArray[p];
  32807. path2 = pathArray[p + 1];
  32808. if (i === minlg) {
  32809. vertex1 = path1[0];
  32810. vertex2 = path2[0];
  32811. }
  32812. else {
  32813. vertex1 = path1[i];
  32814. vertex2 = path2[i];
  32815. }
  32816. vectlg = vertex2.subtract(vertex1).length();
  32817. dist = vectlg + vTotalDistance[i];
  32818. vs[i].push(dist);
  32819. vTotalDistance[i] = dist;
  32820. }
  32821. if (closeArray && vertex2 && vertex1) {
  32822. path1 = pathArray[p];
  32823. path2 = pathArray[0];
  32824. if (i === minlg) {
  32825. vertex2 = path2[0];
  32826. }
  32827. vectlg = vertex2.subtract(vertex1).length();
  32828. dist = vectlg + vTotalDistance[i];
  32829. vTotalDistance[i] = dist;
  32830. }
  32831. }
  32832. // uvs
  32833. var u;
  32834. var v;
  32835. if (customUV) {
  32836. for (p = 0; p < customUV.length; p++) {
  32837. uvs.push(customUV[p].x, customUV[p].y);
  32838. }
  32839. }
  32840. else {
  32841. for (p = 0; p < pathArray.length; p++) {
  32842. for (i = 0; i < minlg + closePathCorr; i++) {
  32843. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32844. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32845. if (invertUV) {
  32846. uvs.push(v, u);
  32847. }
  32848. else {
  32849. uvs.push(u, v);
  32850. }
  32851. }
  32852. }
  32853. }
  32854. // indices
  32855. p = 0; // path index
  32856. var pi = 0; // positions array index
  32857. var l1 = lg[p] - 1; // path1 length
  32858. var l2 = lg[p + 1] - 1; // path2 length
  32859. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32860. var shft = idx[1] - idx[0]; // shift
  32861. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32862. while (pi <= min && p < path1nb) {
  32863. // 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
  32864. indices.push(pi, pi + shft, pi + 1);
  32865. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32866. pi += 1;
  32867. if (pi === min) {
  32868. p++;
  32869. if (p === lg.length - 1) {
  32870. shft = idx[0] - idx[p];
  32871. l1 = lg[p] - 1;
  32872. l2 = lg[0] - 1;
  32873. }
  32874. else {
  32875. shft = idx[p + 1] - idx[p];
  32876. l1 = lg[p] - 1;
  32877. l2 = lg[p + 1] - 1;
  32878. }
  32879. pi = idx[p];
  32880. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32881. }
  32882. }
  32883. // normals
  32884. VertexData.ComputeNormals(positions, indices, normals);
  32885. if (closePath) {
  32886. var indexFirst = 0;
  32887. var indexLast = 0;
  32888. for (p = 0; p < pathArray.length; p++) {
  32889. indexFirst = idx[p] * 3;
  32890. if (p + 1 < pathArray.length) {
  32891. indexLast = (idx[p + 1] - 1) * 3;
  32892. }
  32893. else {
  32894. indexLast = normals.length - 3;
  32895. }
  32896. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32897. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32898. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32899. normals[indexLast] = normals[indexFirst];
  32900. normals[indexLast + 1] = normals[indexFirst + 1];
  32901. normals[indexLast + 2] = normals[indexFirst + 2];
  32902. }
  32903. }
  32904. // sides
  32905. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32906. // Colors
  32907. var colors = null;
  32908. if (customColors) {
  32909. colors = new Float32Array(customColors.length * 4);
  32910. for (var c = 0; c < customColors.length; c++) {
  32911. colors[c * 4] = customColors[c].r;
  32912. colors[c * 4 + 1] = customColors[c].g;
  32913. colors[c * 4 + 2] = customColors[c].b;
  32914. colors[c * 4 + 3] = customColors[c].a;
  32915. }
  32916. }
  32917. // Result
  32918. var vertexData = new VertexData();
  32919. var positions32 = new Float32Array(positions);
  32920. var normals32 = new Float32Array(normals);
  32921. var uvs32 = new Float32Array(uvs);
  32922. vertexData.indices = indices;
  32923. vertexData.positions = positions32;
  32924. vertexData.normals = normals32;
  32925. vertexData.uvs = uvs32;
  32926. if (colors) {
  32927. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32928. }
  32929. if (closePath) {
  32930. vertexData._idx = idx;
  32931. }
  32932. return vertexData;
  32933. };
  32934. /**
  32935. * Creates the VertexData of the Box.
  32936. */
  32937. VertexData.CreateBox = function (options) {
  32938. var normalsSource = [
  32939. new BABYLON.Vector3(0, 0, 1),
  32940. new BABYLON.Vector3(0, 0, -1),
  32941. new BABYLON.Vector3(1, 0, 0),
  32942. new BABYLON.Vector3(-1, 0, 0),
  32943. new BABYLON.Vector3(0, 1, 0),
  32944. new BABYLON.Vector3(0, -1, 0)
  32945. ];
  32946. var indices = [];
  32947. var positions = [];
  32948. var normals = [];
  32949. var uvs = [];
  32950. var width = options.width || options.size || 1;
  32951. var height = options.height || options.size || 1;
  32952. var depth = options.depth || options.size || 1;
  32953. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32954. var faceUV = options.faceUV || new Array(6);
  32955. var faceColors = options.faceColors;
  32956. var colors = [];
  32957. // default face colors and UV if undefined
  32958. for (var f = 0; f < 6; f++) {
  32959. if (faceUV[f] === undefined) {
  32960. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32961. }
  32962. if (faceColors && faceColors[f] === undefined) {
  32963. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32964. }
  32965. }
  32966. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32967. // Create each face in turn.
  32968. for (var index = 0; index < normalsSource.length; index++) {
  32969. var normal = normalsSource[index];
  32970. // Get two vectors perpendicular to the face normal and to each other.
  32971. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32972. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32973. // Six indices (two triangles) per face.
  32974. var verticesLength = positions.length / 3;
  32975. indices.push(verticesLength);
  32976. indices.push(verticesLength + 1);
  32977. indices.push(verticesLength + 2);
  32978. indices.push(verticesLength);
  32979. indices.push(verticesLength + 2);
  32980. indices.push(verticesLength + 3);
  32981. // Four vertices per face.
  32982. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32983. positions.push(vertex.x, vertex.y, vertex.z);
  32984. normals.push(normal.x, normal.y, normal.z);
  32985. uvs.push(faceUV[index].z, faceUV[index].w);
  32986. if (faceColors) {
  32987. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32988. }
  32989. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32990. positions.push(vertex.x, vertex.y, vertex.z);
  32991. normals.push(normal.x, normal.y, normal.z);
  32992. uvs.push(faceUV[index].x, faceUV[index].w);
  32993. if (faceColors) {
  32994. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32995. }
  32996. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32997. positions.push(vertex.x, vertex.y, vertex.z);
  32998. normals.push(normal.x, normal.y, normal.z);
  32999. uvs.push(faceUV[index].x, faceUV[index].y);
  33000. if (faceColors) {
  33001. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33002. }
  33003. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33004. positions.push(vertex.x, vertex.y, vertex.z);
  33005. normals.push(normal.x, normal.y, normal.z);
  33006. uvs.push(faceUV[index].z, faceUV[index].y);
  33007. if (faceColors) {
  33008. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33009. }
  33010. }
  33011. // sides
  33012. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33013. // Result
  33014. var vertexData = new VertexData();
  33015. vertexData.indices = indices;
  33016. vertexData.positions = positions;
  33017. vertexData.normals = normals;
  33018. vertexData.uvs = uvs;
  33019. if (faceColors) {
  33020. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33021. vertexData.colors = totalColors;
  33022. }
  33023. return vertexData;
  33024. };
  33025. /**
  33026. * Creates the VertexData of the Sphere.
  33027. */
  33028. VertexData.CreateSphere = function (options) {
  33029. var segments = options.segments || 32;
  33030. var diameterX = options.diameterX || options.diameter || 1;
  33031. var diameterY = options.diameterY || options.diameter || 1;
  33032. var diameterZ = options.diameterZ || options.diameter || 1;
  33033. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33034. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33036. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33037. var totalZRotationSteps = 2 + segments;
  33038. var totalYRotationSteps = 2 * totalZRotationSteps;
  33039. var indices = [];
  33040. var positions = [];
  33041. var normals = [];
  33042. var uvs = [];
  33043. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33044. var normalizedZ = zRotationStep / totalZRotationSteps;
  33045. var angleZ = normalizedZ * Math.PI * slice;
  33046. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33047. var normalizedY = yRotationStep / totalYRotationSteps;
  33048. var angleY = normalizedY * Math.PI * 2 * arc;
  33049. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33050. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33051. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33052. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33053. var vertex = complete.multiply(radius);
  33054. var normal = complete.divide(radius).normalize();
  33055. positions.push(vertex.x, vertex.y, vertex.z);
  33056. normals.push(normal.x, normal.y, normal.z);
  33057. uvs.push(normalizedY, normalizedZ);
  33058. }
  33059. if (zRotationStep > 0) {
  33060. var verticesCount = positions.length / 3;
  33061. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33062. indices.push((firstIndex));
  33063. indices.push((firstIndex + 1));
  33064. indices.push(firstIndex + totalYRotationSteps + 1);
  33065. indices.push((firstIndex + totalYRotationSteps + 1));
  33066. indices.push((firstIndex + 1));
  33067. indices.push((firstIndex + totalYRotationSteps + 2));
  33068. }
  33069. }
  33070. }
  33071. // Sides
  33072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33073. // Result
  33074. var vertexData = new VertexData();
  33075. vertexData.indices = indices;
  33076. vertexData.positions = positions;
  33077. vertexData.normals = normals;
  33078. vertexData.uvs = uvs;
  33079. return vertexData;
  33080. };
  33081. /**
  33082. * Creates the VertexData of the Cylinder or Cone.
  33083. */
  33084. VertexData.CreateCylinder = function (options) {
  33085. var height = options.height || 2;
  33086. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33087. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33088. var tessellation = options.tessellation || 24;
  33089. var subdivisions = options.subdivisions || 1;
  33090. var hasRings = options.hasRings ? true : false;
  33091. var enclose = options.enclose ? true : false;
  33092. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33093. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33094. var faceUV = options.faceUV || new Array(3);
  33095. var faceColors = options.faceColors;
  33096. // default face colors and UV if undefined
  33097. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33098. var ringNb = (hasRings) ? subdivisions : 1;
  33099. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33100. var f;
  33101. for (f = 0; f < surfaceNb; f++) {
  33102. if (faceColors && faceColors[f] === undefined) {
  33103. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33104. }
  33105. }
  33106. for (f = 0; f < surfaceNb; f++) {
  33107. if (faceUV && faceUV[f] === undefined) {
  33108. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33109. }
  33110. }
  33111. var indices = new Array();
  33112. var positions = new Array();
  33113. var normals = new Array();
  33114. var uvs = new Array();
  33115. var colors = new Array();
  33116. var angle_step = Math.PI * 2 * arc / tessellation;
  33117. var angle;
  33118. var h;
  33119. var radius;
  33120. var tan = (diameterBottom - diameterTop) / 2 / height;
  33121. var ringVertex = BABYLON.Vector3.Zero();
  33122. var ringNormal = BABYLON.Vector3.Zero();
  33123. var ringFirstVertex = BABYLON.Vector3.Zero();
  33124. var ringFirstNormal = BABYLON.Vector3.Zero();
  33125. var quadNormal = BABYLON.Vector3.Zero();
  33126. var Y = BABYLON.Axis.Y;
  33127. // positions, normals, uvs
  33128. var i;
  33129. var j;
  33130. var r;
  33131. var ringIdx = 1;
  33132. var s = 1; // surface index
  33133. var cs = 0;
  33134. var v = 0;
  33135. for (i = 0; i <= subdivisions; i++) {
  33136. h = i / subdivisions;
  33137. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33138. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33139. for (r = 0; r < ringIdx; r++) {
  33140. if (hasRings) {
  33141. s += r;
  33142. }
  33143. if (enclose) {
  33144. s += 2 * r;
  33145. }
  33146. for (j = 0; j <= tessellation; j++) {
  33147. angle = j * angle_step;
  33148. // position
  33149. ringVertex.x = Math.cos(-angle) * radius;
  33150. ringVertex.y = -height / 2 + h * height;
  33151. ringVertex.z = Math.sin(-angle) * radius;
  33152. // normal
  33153. if (diameterTop === 0 && i === subdivisions) {
  33154. // if no top cap, reuse former normals
  33155. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33156. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33157. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33158. }
  33159. else {
  33160. ringNormal.x = ringVertex.x;
  33161. ringNormal.z = ringVertex.z;
  33162. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33163. ringNormal.normalize();
  33164. }
  33165. // keep first ring vertex values for enclose
  33166. if (j === 0) {
  33167. ringFirstVertex.copyFrom(ringVertex);
  33168. ringFirstNormal.copyFrom(ringNormal);
  33169. }
  33170. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33171. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33172. if (hasRings) {
  33173. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33174. }
  33175. else {
  33176. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33177. }
  33178. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33179. if (faceColors) {
  33180. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33181. }
  33182. }
  33183. // if enclose, add four vertices and their dedicated normals
  33184. if (arc !== 1 && enclose) {
  33185. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33186. positions.push(0, ringVertex.y, 0);
  33187. positions.push(0, ringVertex.y, 0);
  33188. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33189. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33190. quadNormal.normalize();
  33191. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33192. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33193. quadNormal.normalize();
  33194. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33195. if (hasRings) {
  33196. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33197. }
  33198. else {
  33199. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33200. }
  33201. uvs.push(faceUV[s + 1].x, v);
  33202. uvs.push(faceUV[s + 1].z, v);
  33203. if (hasRings) {
  33204. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33205. }
  33206. else {
  33207. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33208. }
  33209. uvs.push(faceUV[s + 2].x, v);
  33210. uvs.push(faceUV[s + 2].z, v);
  33211. if (faceColors) {
  33212. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33213. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33214. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33215. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33216. }
  33217. }
  33218. if (cs !== s) {
  33219. cs = s;
  33220. }
  33221. }
  33222. }
  33223. // indices
  33224. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33225. var s;
  33226. i = 0;
  33227. for (s = 0; s < subdivisions; s++) {
  33228. var i0 = 0;
  33229. var i1 = 0;
  33230. var i2 = 0;
  33231. var i3 = 0;
  33232. for (j = 0; j < tessellation; j++) {
  33233. i0 = i * (e + 1) + j;
  33234. i1 = (i + 1) * (e + 1) + j;
  33235. i2 = i * (e + 1) + (j + 1);
  33236. i3 = (i + 1) * (e + 1) + (j + 1);
  33237. indices.push(i0, i1, i2);
  33238. indices.push(i3, i2, i1);
  33239. }
  33240. if (arc !== 1 && enclose) {
  33241. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33242. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33243. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33244. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33245. }
  33246. i = (hasRings) ? (i + 2) : (i + 1);
  33247. }
  33248. // Caps
  33249. var createCylinderCap = function (isTop) {
  33250. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33251. if (radius === 0) {
  33252. return;
  33253. }
  33254. // Cap positions, normals & uvs
  33255. var angle;
  33256. var circleVector;
  33257. var i;
  33258. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33259. var c = null;
  33260. if (faceColors) {
  33261. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33262. }
  33263. // cap center
  33264. var vbase = positions.length / 3;
  33265. var offset = isTop ? height / 2 : -height / 2;
  33266. var center = new BABYLON.Vector3(0, offset, 0);
  33267. positions.push(center.x, center.y, center.z);
  33268. normals.push(0, isTop ? 1 : -1, 0);
  33269. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33270. if (c) {
  33271. colors.push(c.r, c.g, c.b, c.a);
  33272. }
  33273. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33274. for (i = 0; i <= tessellation; i++) {
  33275. angle = Math.PI * 2 * i * arc / tessellation;
  33276. var cos = Math.cos(-angle);
  33277. var sin = Math.sin(-angle);
  33278. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33279. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33280. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33281. normals.push(0, isTop ? 1 : -1, 0);
  33282. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33283. if (c) {
  33284. colors.push(c.r, c.g, c.b, c.a);
  33285. }
  33286. }
  33287. // Cap indices
  33288. for (i = 0; i < tessellation; i++) {
  33289. if (!isTop) {
  33290. indices.push(vbase);
  33291. indices.push(vbase + (i + 1));
  33292. indices.push(vbase + (i + 2));
  33293. }
  33294. else {
  33295. indices.push(vbase);
  33296. indices.push(vbase + (i + 2));
  33297. indices.push(vbase + (i + 1));
  33298. }
  33299. }
  33300. };
  33301. // add caps to geometry
  33302. createCylinderCap(false);
  33303. createCylinderCap(true);
  33304. // Sides
  33305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33306. var vertexData = new VertexData();
  33307. vertexData.indices = indices;
  33308. vertexData.positions = positions;
  33309. vertexData.normals = normals;
  33310. vertexData.uvs = uvs;
  33311. if (faceColors) {
  33312. vertexData.colors = colors;
  33313. }
  33314. return vertexData;
  33315. };
  33316. /**
  33317. * Creates the VertexData of the Torus.
  33318. */
  33319. VertexData.CreateTorus = function (options) {
  33320. var indices = [];
  33321. var positions = [];
  33322. var normals = [];
  33323. var uvs = [];
  33324. var diameter = options.diameter || 1;
  33325. var thickness = options.thickness || 0.5;
  33326. var tessellation = options.tessellation || 16;
  33327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33328. var stride = tessellation + 1;
  33329. for (var i = 0; i <= tessellation; i++) {
  33330. var u = i / tessellation;
  33331. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33332. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33333. for (var j = 0; j <= tessellation; j++) {
  33334. var v = 1 - j / tessellation;
  33335. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33336. var dx = Math.cos(innerAngle);
  33337. var dy = Math.sin(innerAngle);
  33338. // Create a vertex.
  33339. var normal = new BABYLON.Vector3(dx, dy, 0);
  33340. var position = normal.scale(thickness / 2);
  33341. var textureCoordinate = new BABYLON.Vector2(u, v);
  33342. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33343. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33344. positions.push(position.x, position.y, position.z);
  33345. normals.push(normal.x, normal.y, normal.z);
  33346. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33347. // And create indices for two triangles.
  33348. var nextI = (i + 1) % stride;
  33349. var nextJ = (j + 1) % stride;
  33350. indices.push(i * stride + j);
  33351. indices.push(i * stride + nextJ);
  33352. indices.push(nextI * stride + j);
  33353. indices.push(i * stride + nextJ);
  33354. indices.push(nextI * stride + nextJ);
  33355. indices.push(nextI * stride + j);
  33356. }
  33357. }
  33358. // Sides
  33359. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33360. // Result
  33361. var vertexData = new VertexData();
  33362. vertexData.indices = indices;
  33363. vertexData.positions = positions;
  33364. vertexData.normals = normals;
  33365. vertexData.uvs = uvs;
  33366. return vertexData;
  33367. };
  33368. /**
  33369. * Creates the VertexData of the LineSystem.
  33370. */
  33371. VertexData.CreateLineSystem = function (options) {
  33372. var indices = [];
  33373. var positions = [];
  33374. var lines = options.lines;
  33375. var colors = options.colors;
  33376. var vertexColors = [];
  33377. var idx = 0;
  33378. for (var l = 0; l < lines.length; l++) {
  33379. var points = lines[l];
  33380. for (var index = 0; index < points.length; index++) {
  33381. positions.push(points[index].x, points[index].y, points[index].z);
  33382. if (colors) {
  33383. var color = colors[l];
  33384. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33385. }
  33386. if (index > 0) {
  33387. indices.push(idx - 1);
  33388. indices.push(idx);
  33389. }
  33390. idx++;
  33391. }
  33392. }
  33393. var vertexData = new VertexData();
  33394. vertexData.indices = indices;
  33395. vertexData.positions = positions;
  33396. if (colors) {
  33397. vertexData.colors = vertexColors;
  33398. }
  33399. return vertexData;
  33400. };
  33401. /**
  33402. * Create the VertexData of the DashedLines.
  33403. */
  33404. VertexData.CreateDashedLines = function (options) {
  33405. var dashSize = options.dashSize || 3;
  33406. var gapSize = options.gapSize || 1;
  33407. var dashNb = options.dashNb || 200;
  33408. var points = options.points;
  33409. var positions = new Array();
  33410. var indices = new Array();
  33411. var curvect = BABYLON.Vector3.Zero();
  33412. var lg = 0;
  33413. var nb = 0;
  33414. var shft = 0;
  33415. var dashshft = 0;
  33416. var curshft = 0;
  33417. var idx = 0;
  33418. var i = 0;
  33419. for (i = 0; i < points.length - 1; i++) {
  33420. points[i + 1].subtractToRef(points[i], curvect);
  33421. lg += curvect.length();
  33422. }
  33423. shft = lg / dashNb;
  33424. dashshft = dashSize * shft / (dashSize + gapSize);
  33425. for (i = 0; i < points.length - 1; i++) {
  33426. points[i + 1].subtractToRef(points[i], curvect);
  33427. nb = Math.floor(curvect.length() / shft);
  33428. curvect.normalize();
  33429. for (var j = 0; j < nb; j++) {
  33430. curshft = shft * j;
  33431. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33432. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33433. indices.push(idx, idx + 1);
  33434. idx += 2;
  33435. }
  33436. }
  33437. // Result
  33438. var vertexData = new VertexData();
  33439. vertexData.positions = positions;
  33440. vertexData.indices = indices;
  33441. return vertexData;
  33442. };
  33443. /**
  33444. * Creates the VertexData of the Ground.
  33445. */
  33446. VertexData.CreateGround = function (options) {
  33447. var indices = [];
  33448. var positions = [];
  33449. var normals = [];
  33450. var uvs = [];
  33451. var row, col;
  33452. var width = options.width || 1;
  33453. var height = options.height || 1;
  33454. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33455. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33456. for (row = 0; row <= subdivisionsY; row++) {
  33457. for (col = 0; col <= subdivisionsX; col++) {
  33458. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33459. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33460. positions.push(position.x, position.y, position.z);
  33461. normals.push(normal.x, normal.y, normal.z);
  33462. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33463. }
  33464. }
  33465. for (row = 0; row < subdivisionsY; row++) {
  33466. for (col = 0; col < subdivisionsX; col++) {
  33467. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33468. indices.push(col + 1 + row * (subdivisionsX + 1));
  33469. indices.push(col + row * (subdivisionsX + 1));
  33470. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33471. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33472. indices.push(col + row * (subdivisionsX + 1));
  33473. }
  33474. }
  33475. // Result
  33476. var vertexData = new VertexData();
  33477. vertexData.indices = indices;
  33478. vertexData.positions = positions;
  33479. vertexData.normals = normals;
  33480. vertexData.uvs = uvs;
  33481. return vertexData;
  33482. };
  33483. /**
  33484. * Creates the VertexData of the TiledGround.
  33485. */
  33486. VertexData.CreateTiledGround = function (options) {
  33487. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33488. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33489. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33490. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33491. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33492. var precision = options.precision || { w: 1, h: 1 };
  33493. var indices = new Array();
  33494. var positions = new Array();
  33495. var normals = new Array();
  33496. var uvs = new Array();
  33497. var row, col, tileRow, tileCol;
  33498. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33499. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33500. precision.w = (precision.w < 1) ? 1 : precision.w;
  33501. precision.h = (precision.h < 1) ? 1 : precision.h;
  33502. var tileSize = {
  33503. 'w': (xmax - xmin) / subdivisions.w,
  33504. 'h': (zmax - zmin) / subdivisions.h
  33505. };
  33506. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33507. // Indices
  33508. var base = positions.length / 3;
  33509. var rowLength = precision.w + 1;
  33510. for (row = 0; row < precision.h; row++) {
  33511. for (col = 0; col < precision.w; col++) {
  33512. var square = [
  33513. base + col + row * rowLength,
  33514. base + (col + 1) + row * rowLength,
  33515. base + (col + 1) + (row + 1) * rowLength,
  33516. base + col + (row + 1) * rowLength
  33517. ];
  33518. indices.push(square[1]);
  33519. indices.push(square[2]);
  33520. indices.push(square[3]);
  33521. indices.push(square[0]);
  33522. indices.push(square[1]);
  33523. indices.push(square[3]);
  33524. }
  33525. }
  33526. // Position, normals and uvs
  33527. var position = BABYLON.Vector3.Zero();
  33528. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33529. for (row = 0; row <= precision.h; row++) {
  33530. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33531. for (col = 0; col <= precision.w; col++) {
  33532. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33533. position.y = 0;
  33534. positions.push(position.x, position.y, position.z);
  33535. normals.push(normal.x, normal.y, normal.z);
  33536. uvs.push(col / precision.w, row / precision.h);
  33537. }
  33538. }
  33539. }
  33540. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33541. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33542. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33543. }
  33544. }
  33545. // Result
  33546. var vertexData = new VertexData();
  33547. vertexData.indices = indices;
  33548. vertexData.positions = positions;
  33549. vertexData.normals = normals;
  33550. vertexData.uvs = uvs;
  33551. return vertexData;
  33552. };
  33553. /**
  33554. * Creates the VertexData of the Ground designed from a heightmap.
  33555. */
  33556. VertexData.CreateGroundFromHeightMap = function (options) {
  33557. var indices = [];
  33558. var positions = [];
  33559. var normals = [];
  33560. var uvs = [];
  33561. var row, col;
  33562. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33563. // Vertices
  33564. for (row = 0; row <= options.subdivisions; row++) {
  33565. for (col = 0; col <= options.subdivisions; col++) {
  33566. 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));
  33567. // Compute height
  33568. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33569. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33570. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33571. var r = options.buffer[pos] / 255.0;
  33572. var g = options.buffer[pos + 1] / 255.0;
  33573. var b = options.buffer[pos + 2] / 255.0;
  33574. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33575. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33576. // Add vertex
  33577. positions.push(position.x, position.y, position.z);
  33578. normals.push(0, 0, 0);
  33579. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33580. }
  33581. }
  33582. // Indices
  33583. for (row = 0; row < options.subdivisions; row++) {
  33584. for (col = 0; col < options.subdivisions; col++) {
  33585. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33586. indices.push(col + 1 + row * (options.subdivisions + 1));
  33587. indices.push(col + row * (options.subdivisions + 1));
  33588. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33589. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33590. indices.push(col + row * (options.subdivisions + 1));
  33591. }
  33592. }
  33593. // Normals
  33594. VertexData.ComputeNormals(positions, indices, normals);
  33595. // Result
  33596. var vertexData = new VertexData();
  33597. vertexData.indices = indices;
  33598. vertexData.positions = positions;
  33599. vertexData.normals = normals;
  33600. vertexData.uvs = uvs;
  33601. return vertexData;
  33602. };
  33603. /**
  33604. * Creates the VertexData of the Plane.
  33605. */
  33606. VertexData.CreatePlane = function (options) {
  33607. var indices = [];
  33608. var positions = [];
  33609. var normals = [];
  33610. var uvs = [];
  33611. var width = options.width || options.size || 1;
  33612. var height = options.height || options.size || 1;
  33613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33614. // Vertices
  33615. var halfWidth = width / 2.0;
  33616. var halfHeight = height / 2.0;
  33617. positions.push(-halfWidth, -halfHeight, 0);
  33618. normals.push(0, 0, -1.0);
  33619. uvs.push(0.0, 0.0);
  33620. positions.push(halfWidth, -halfHeight, 0);
  33621. normals.push(0, 0, -1.0);
  33622. uvs.push(1.0, 0.0);
  33623. positions.push(halfWidth, halfHeight, 0);
  33624. normals.push(0, 0, -1.0);
  33625. uvs.push(1.0, 1.0);
  33626. positions.push(-halfWidth, halfHeight, 0);
  33627. normals.push(0, 0, -1.0);
  33628. uvs.push(0.0, 1.0);
  33629. // Indices
  33630. indices.push(0);
  33631. indices.push(1);
  33632. indices.push(2);
  33633. indices.push(0);
  33634. indices.push(2);
  33635. indices.push(3);
  33636. // Sides
  33637. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33638. // Result
  33639. var vertexData = new VertexData();
  33640. vertexData.indices = indices;
  33641. vertexData.positions = positions;
  33642. vertexData.normals = normals;
  33643. vertexData.uvs = uvs;
  33644. return vertexData;
  33645. };
  33646. /**
  33647. * Creates the VertexData of the Disc or regular Polygon.
  33648. */
  33649. VertexData.CreateDisc = function (options) {
  33650. var positions = new Array();
  33651. var indices = new Array();
  33652. var normals = new Array();
  33653. var uvs = new Array();
  33654. var radius = options.radius || 0.5;
  33655. var tessellation = options.tessellation || 64;
  33656. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33658. // positions and uvs
  33659. positions.push(0, 0, 0); // disc center first
  33660. uvs.push(0.5, 0.5);
  33661. var theta = Math.PI * 2 * arc;
  33662. var step = theta / tessellation;
  33663. for (var a = 0; a < theta; a += step) {
  33664. var x = Math.cos(a);
  33665. var y = Math.sin(a);
  33666. var u = (x + 1) / 2;
  33667. var v = (1 - y) / 2;
  33668. positions.push(radius * x, radius * y, 0);
  33669. uvs.push(u, v);
  33670. }
  33671. if (arc === 1) {
  33672. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33673. uvs.push(uvs[2], uvs[3]);
  33674. }
  33675. //indices
  33676. var vertexNb = positions.length / 3;
  33677. for (var i = 1; i < vertexNb - 1; i++) {
  33678. indices.push(i + 1, 0, i);
  33679. }
  33680. // result
  33681. VertexData.ComputeNormals(positions, indices, normals);
  33682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33683. var vertexData = new VertexData();
  33684. vertexData.indices = indices;
  33685. vertexData.positions = positions;
  33686. vertexData.normals = normals;
  33687. vertexData.uvs = uvs;
  33688. return vertexData;
  33689. };
  33690. /**
  33691. * Re-creates the VertexData of the Polygon for sideOrientation.
  33692. */
  33693. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33694. var faceUV = fUV || new Array(3);
  33695. var faceColors = fColors;
  33696. var colors = [];
  33697. // default face colors and UV if undefined
  33698. for (var f = 0; f < 3; f++) {
  33699. if (faceUV[f] === undefined) {
  33700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33701. }
  33702. if (faceColors && faceColors[f] === undefined) {
  33703. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33704. }
  33705. }
  33706. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33707. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33708. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33709. var indices = polygon.getIndices();
  33710. // set face colours and textures
  33711. var idx = 0;
  33712. var face = 0;
  33713. for (var index = 0; index < normals.length; index += 3) {
  33714. //Edge Face no. 1
  33715. if (Math.abs(normals[index + 1]) < 0.001) {
  33716. face = 1;
  33717. }
  33718. //Top Face no. 0
  33719. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33720. face = 0;
  33721. }
  33722. //Bottom Face no. 2
  33723. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33724. face = 2;
  33725. }
  33726. idx = index / 3;
  33727. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33728. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33729. if (faceColors) {
  33730. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33731. }
  33732. }
  33733. // sides
  33734. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33735. // Result
  33736. var vertexData = new VertexData();
  33737. vertexData.indices = indices;
  33738. vertexData.positions = positions;
  33739. vertexData.normals = normals;
  33740. vertexData.uvs = uvs;
  33741. if (faceColors) {
  33742. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33743. vertexData.colors = totalColors;
  33744. }
  33745. return vertexData;
  33746. };
  33747. /**
  33748. * Creates the VertexData of the IcoSphere.
  33749. */
  33750. VertexData.CreateIcoSphere = function (options) {
  33751. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33752. var radius = options.radius || 1;
  33753. var flat = (options.flat === undefined) ? true : options.flat;
  33754. var subdivisions = options.subdivisions || 4;
  33755. var radiusX = options.radiusX || radius;
  33756. var radiusY = options.radiusY || radius;
  33757. var radiusZ = options.radiusZ || radius;
  33758. var t = (1 + Math.sqrt(5)) / 2;
  33759. // 12 vertex x,y,z
  33760. var ico_vertices = [
  33761. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33762. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33763. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33764. ];
  33765. // index of 3 vertex makes a face of icopshere
  33766. var ico_indices = [
  33767. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33768. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33769. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33770. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33771. ];
  33772. // vertex for uv have aliased position, not for UV
  33773. var vertices_unalias_id = [
  33774. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33775. // vertex alias
  33776. 0,
  33777. 2,
  33778. 3,
  33779. 3,
  33780. 3,
  33781. 4,
  33782. 7,
  33783. 8,
  33784. 9,
  33785. 9,
  33786. 10,
  33787. 11 // 23: B + 12
  33788. ];
  33789. // uv as integer step (not pixels !)
  33790. var ico_vertexuv = [
  33791. 5, 1, 3, 1, 6, 4, 0, 0,
  33792. 5, 3, 4, 2, 2, 2, 4, 0,
  33793. 2, 0, 1, 1, 6, 0, 6, 2,
  33794. // vertex alias (for same vertex on different faces)
  33795. 0, 4,
  33796. 3, 3,
  33797. 4, 4,
  33798. 3, 1,
  33799. 4, 2,
  33800. 4, 4,
  33801. 0, 2,
  33802. 1, 1,
  33803. 2, 2,
  33804. 3, 3,
  33805. 1, 3,
  33806. 2, 4 // 23: B + 12
  33807. ];
  33808. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33809. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33810. // First island of uv mapping
  33811. // v = 4h 3+ 2
  33812. // v = 3h 9+ 4
  33813. // v = 2h 9+ 5 B
  33814. // v = 1h 9 1 0
  33815. // v = 0h 3 8 7 A
  33816. // u = 0 1 2 3 4 5 6 *a
  33817. // Second island of uv mapping
  33818. // v = 4h 0+ B+ 4+
  33819. // v = 3h A+ 2+
  33820. // v = 2h 7+ 6 3+
  33821. // v = 1h 8+ 3+
  33822. // v = 0h
  33823. // u = 0 1 2 3 4 5 6 *a
  33824. // Face layout on texture UV mapping
  33825. // ============
  33826. // \ 4 /\ 16 / ======
  33827. // \ / \ / /\ 11 /
  33828. // \/ 7 \/ / \ /
  33829. // ======= / 10 \/
  33830. // /\ 17 /\ =======
  33831. // / \ / \ \ 15 /\
  33832. // / 8 \/ 12 \ \ / \
  33833. // ============ \/ 6 \
  33834. // \ 18 /\ ============
  33835. // \ / \ \ 5 /\ 0 /
  33836. // \/ 13 \ \ / \ /
  33837. // ======= \/ 1 \/
  33838. // =============
  33839. // /\ 19 /\ 2 /\
  33840. // / \ / \ / \
  33841. // / 14 \/ 9 \/ 3 \
  33842. // ===================
  33843. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33844. var ustep = 138 / 1024;
  33845. var vstep = 239 / 1024;
  33846. var uoffset = 60 / 1024;
  33847. var voffset = 26 / 1024;
  33848. // Second island should have margin, not to touch the first island
  33849. // avoid any borderline artefact in pixel rounding
  33850. var island_u_offset = -40 / 1024;
  33851. var island_v_offset = +20 / 1024;
  33852. // face is either island 0 or 1 :
  33853. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33854. var island = [
  33855. 0, 0, 0, 0, 1,
  33856. 0, 0, 1, 1, 0,
  33857. 0, 0, 1, 1, 0,
  33858. 0, 1, 1, 1, 0 // 15 - 19
  33859. ];
  33860. var indices = new Array();
  33861. var positions = new Array();
  33862. var normals = new Array();
  33863. var uvs = new Array();
  33864. var current_indice = 0;
  33865. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33866. var face_vertex_pos = new Array(3);
  33867. var face_vertex_uv = new Array(3);
  33868. var v012;
  33869. for (v012 = 0; v012 < 3; v012++) {
  33870. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33871. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33872. }
  33873. // create all with normals
  33874. for (var face = 0; face < 20; face++) {
  33875. // 3 vertex per face
  33876. for (v012 = 0; v012 < 3; v012++) {
  33877. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33878. var v_id = ico_indices[3 * face + v012];
  33879. // vertex have 3D position (x,y,z)
  33880. 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]);
  33881. // Normalize to get normal, then scale to radius
  33882. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33883. // uv Coordinates from vertex ID
  33884. 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);
  33885. }
  33886. // Subdivide the face (interpolate pos, norm, uv)
  33887. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33888. // - norm is linear interpolation of vertex corner normal
  33889. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33890. // - uv is linear interpolation
  33891. //
  33892. // Topology is as below for sub-divide by 2
  33893. // vertex shown as v0,v1,v2
  33894. // interp index is i1 to progress in range [v0,v1[
  33895. // interp index is i2 to progress in range [v0,v2[
  33896. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33897. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33898. //
  33899. //
  33900. // i2 v2
  33901. // ^ ^
  33902. // / / \
  33903. // / / \
  33904. // / / \
  33905. // / / (0,1) \
  33906. // / #---------\
  33907. // / / \ (0,0)'/ \
  33908. // / / \ / \
  33909. // / / \ / \
  33910. // / / (0,0) \ / (1,0) \
  33911. // / #---------#---------\
  33912. // v0 v1
  33913. //
  33914. // --------------------> i1
  33915. //
  33916. // interp of (i1,i2):
  33917. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33918. // along i1 : lerp(x0,x1, i1/(S-i2))
  33919. //
  33920. // centroid of triangle is needed to get help normal computation
  33921. // (c1,c2) are used for centroid location
  33922. var interp_vertex = function (i1, i2, c1, c2) {
  33923. // vertex is interpolated from
  33924. // - face_vertex_pos[0..2]
  33925. // - face_vertex_uv[0..2]
  33926. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33927. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33928. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33929. pos_interp.normalize();
  33930. var vertex_normal;
  33931. if (flat) {
  33932. // in flat mode, recalculate normal as face centroid normal
  33933. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33934. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33935. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33936. }
  33937. else {
  33938. // in smooth mode, recalculate normal from each single vertex position
  33939. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33940. }
  33941. // Vertex normal need correction due to X,Y,Z radius scaling
  33942. vertex_normal.x /= radiusX;
  33943. vertex_normal.y /= radiusY;
  33944. vertex_normal.z /= radiusZ;
  33945. vertex_normal.normalize();
  33946. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33947. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33948. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33949. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33950. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33951. uvs.push(uv_interp.x, uv_interp.y);
  33952. // push each vertex has member of a face
  33953. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33954. indices.push(current_indice);
  33955. current_indice++;
  33956. };
  33957. for (var i2 = 0; i2 < subdivisions; i2++) {
  33958. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33959. // face : (i1,i2) for /\ :
  33960. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33961. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33962. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33963. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33964. if (i1 + i2 + 1 < subdivisions) {
  33965. // face : (i1,i2)' for \/ :
  33966. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33967. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33968. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33969. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33970. }
  33971. }
  33972. }
  33973. }
  33974. // Sides
  33975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33976. // Result
  33977. var vertexData = new VertexData();
  33978. vertexData.indices = indices;
  33979. vertexData.positions = positions;
  33980. vertexData.normals = normals;
  33981. vertexData.uvs = uvs;
  33982. return vertexData;
  33983. };
  33984. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33985. /**
  33986. * Creates the VertexData of the Polyhedron.
  33987. */
  33988. VertexData.CreatePolyhedron = function (options) {
  33989. // provided polyhedron types :
  33990. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33991. // 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)
  33992. var polyhedra = [];
  33993. 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]] };
  33994. 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]] };
  33995. polyhedra[2] = {
  33996. 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]],
  33997. 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]]
  33998. };
  33999. polyhedra[3] = {
  34000. 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]],
  34001. 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]]
  34002. };
  34003. polyhedra[4] = {
  34004. 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]],
  34005. 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]]
  34006. };
  34007. 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]] };
  34008. 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]] };
  34009. 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]] };
  34010. 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]] };
  34011. 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]] };
  34012. 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]] };
  34013. 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]] };
  34014. 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]] };
  34015. 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]] };
  34016. polyhedra[14] = {
  34017. 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]],
  34018. 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]]
  34019. };
  34020. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34021. var size = options.size;
  34022. var sizeX = options.sizeX || size || 1;
  34023. var sizeY = options.sizeY || size || 1;
  34024. var sizeZ = options.sizeZ || size || 1;
  34025. var data = options.custom || polyhedra[type];
  34026. var nbfaces = data.face.length;
  34027. var faceUV = options.faceUV || new Array(nbfaces);
  34028. var faceColors = options.faceColors;
  34029. var flat = (options.flat === undefined) ? true : options.flat;
  34030. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34031. var positions = new Array();
  34032. var indices = new Array();
  34033. var normals = new Array();
  34034. var uvs = new Array();
  34035. var colors = new Array();
  34036. var index = 0;
  34037. var faceIdx = 0; // face cursor in the array "indexes"
  34038. var indexes = new Array();
  34039. var i = 0;
  34040. var f = 0;
  34041. var u, v, ang, x, y, tmp;
  34042. // default face colors and UV if undefined
  34043. if (flat) {
  34044. for (f = 0; f < nbfaces; f++) {
  34045. if (faceColors && faceColors[f] === undefined) {
  34046. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34047. }
  34048. if (faceUV && faceUV[f] === undefined) {
  34049. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34050. }
  34051. }
  34052. }
  34053. if (!flat) {
  34054. for (i = 0; i < data.vertex.length; i++) {
  34055. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34056. uvs.push(0, 0);
  34057. }
  34058. for (f = 0; f < nbfaces; f++) {
  34059. for (i = 0; i < data.face[f].length - 2; i++) {
  34060. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34061. }
  34062. }
  34063. }
  34064. else {
  34065. for (f = 0; f < nbfaces; f++) {
  34066. var fl = data.face[f].length; // number of vertices of the current face
  34067. ang = 2 * Math.PI / fl;
  34068. x = 0.5 * Math.tan(ang / 2);
  34069. y = 0.5;
  34070. // positions, uvs, colors
  34071. for (i = 0; i < fl; i++) {
  34072. // positions
  34073. 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);
  34074. indexes.push(index);
  34075. index++;
  34076. // uvs
  34077. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34078. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34079. uvs.push(u, v);
  34080. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34081. y = x * Math.sin(ang) + y * Math.cos(ang);
  34082. x = tmp;
  34083. // colors
  34084. if (faceColors) {
  34085. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34086. }
  34087. }
  34088. // indices from indexes
  34089. for (i = 0; i < fl - 2; i++) {
  34090. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34091. }
  34092. faceIdx += fl;
  34093. }
  34094. }
  34095. VertexData.ComputeNormals(positions, indices, normals);
  34096. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34097. var vertexData = new VertexData();
  34098. vertexData.positions = positions;
  34099. vertexData.indices = indices;
  34100. vertexData.normals = normals;
  34101. vertexData.uvs = uvs;
  34102. if (faceColors && flat) {
  34103. vertexData.colors = colors;
  34104. }
  34105. return vertexData;
  34106. };
  34107. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34108. /**
  34109. * Creates the VertexData of the Torus Knot.
  34110. */
  34111. VertexData.CreateTorusKnot = function (options) {
  34112. var indices = new Array();
  34113. var positions = new Array();
  34114. var normals = new Array();
  34115. var uvs = new Array();
  34116. var radius = options.radius || 2;
  34117. var tube = options.tube || 0.5;
  34118. var radialSegments = options.radialSegments || 32;
  34119. var tubularSegments = options.tubularSegments || 32;
  34120. var p = options.p || 2;
  34121. var q = options.q || 3;
  34122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34123. // Helper
  34124. var getPos = function (angle) {
  34125. var cu = Math.cos(angle);
  34126. var su = Math.sin(angle);
  34127. var quOverP = q / p * angle;
  34128. var cs = Math.cos(quOverP);
  34129. var tx = radius * (2 + cs) * 0.5 * cu;
  34130. var ty = radius * (2 + cs) * su * 0.5;
  34131. var tz = radius * Math.sin(quOverP) * 0.5;
  34132. return new BABYLON.Vector3(tx, ty, tz);
  34133. };
  34134. // Vertices
  34135. var i;
  34136. var j;
  34137. for (i = 0; i <= radialSegments; i++) {
  34138. var modI = i % radialSegments;
  34139. var u = modI / radialSegments * 2 * p * Math.PI;
  34140. var p1 = getPos(u);
  34141. var p2 = getPos(u + 0.01);
  34142. var tang = p2.subtract(p1);
  34143. var n = p2.add(p1);
  34144. var bitan = BABYLON.Vector3.Cross(tang, n);
  34145. n = BABYLON.Vector3.Cross(bitan, tang);
  34146. bitan.normalize();
  34147. n.normalize();
  34148. for (j = 0; j < tubularSegments; j++) {
  34149. var modJ = j % tubularSegments;
  34150. var v = modJ / tubularSegments * 2 * Math.PI;
  34151. var cx = -tube * Math.cos(v);
  34152. var cy = tube * Math.sin(v);
  34153. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34154. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34155. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34156. uvs.push(i / radialSegments);
  34157. uvs.push(j / tubularSegments);
  34158. }
  34159. }
  34160. for (i = 0; i < radialSegments; i++) {
  34161. for (j = 0; j < tubularSegments; j++) {
  34162. var jNext = (j + 1) % tubularSegments;
  34163. var a = i * tubularSegments + j;
  34164. var b = (i + 1) * tubularSegments + j;
  34165. var c = (i + 1) * tubularSegments + jNext;
  34166. var d = i * tubularSegments + jNext;
  34167. indices.push(d);
  34168. indices.push(b);
  34169. indices.push(a);
  34170. indices.push(d);
  34171. indices.push(c);
  34172. indices.push(b);
  34173. }
  34174. }
  34175. // Normals
  34176. VertexData.ComputeNormals(positions, indices, normals);
  34177. // Sides
  34178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34179. // Result
  34180. var vertexData = new VertexData();
  34181. vertexData.indices = indices;
  34182. vertexData.positions = positions;
  34183. vertexData.normals = normals;
  34184. vertexData.uvs = uvs;
  34185. return vertexData;
  34186. };
  34187. // Tools
  34188. /**
  34189. * @param {any} - positions (number[] or Float32Array)
  34190. * @param {any} - indices (number[] or Uint16Array)
  34191. * @param {any} - normals (number[] or Float32Array)
  34192. * options (optional) :
  34193. * facetPositions : optional array of facet positions (vector3)
  34194. * facetNormals : optional array of facet normals (vector3)
  34195. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34196. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34197. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34198. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34199. * bInfo : optional bounding info, required for facetPartitioning computation
  34200. * useRightHandedSystem: optional boolean to for right handed system computation
  34201. * depthSort : optional boolean to enable the facet depth sort computation
  34202. * distanceTo : optional Vector3 to compute the facet depth from this location
  34203. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34204. */
  34205. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34206. // temporary scalar variables
  34207. var index = 0; // facet index
  34208. var p1p2x = 0.0; // p1p2 vector x coordinate
  34209. var p1p2y = 0.0; // p1p2 vector y coordinate
  34210. var p1p2z = 0.0; // p1p2 vector z coordinate
  34211. var p3p2x = 0.0; // p3p2 vector x coordinate
  34212. var p3p2y = 0.0; // p3p2 vector y coordinate
  34213. var p3p2z = 0.0; // p3p2 vector z coordinate
  34214. var faceNormalx = 0.0; // facet normal x coordinate
  34215. var faceNormaly = 0.0; // facet normal y coordinate
  34216. var faceNormalz = 0.0; // facet normal z coordinate
  34217. var length = 0.0; // facet normal length before normalization
  34218. var v1x = 0; // vector1 x index in the positions array
  34219. var v1y = 0; // vector1 y index in the positions array
  34220. var v1z = 0; // vector1 z index in the positions array
  34221. var v2x = 0; // vector2 x index in the positions array
  34222. var v2y = 0; // vector2 y index in the positions array
  34223. var v2z = 0; // vector2 z index in the positions array
  34224. var v3x = 0; // vector3 x index in the positions array
  34225. var v3y = 0; // vector3 y index in the positions array
  34226. var v3z = 0; // vector3 z index in the positions array
  34227. var computeFacetNormals = false;
  34228. var computeFacetPositions = false;
  34229. var computeFacetPartitioning = false;
  34230. var computeDepthSort = false;
  34231. var faceNormalSign = 1;
  34232. var ratio = 0;
  34233. var distanceTo = null;
  34234. if (options) {
  34235. computeFacetNormals = (options.facetNormals) ? true : false;
  34236. computeFacetPositions = (options.facetPositions) ? true : false;
  34237. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34238. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34239. ratio = options.ratio || 0;
  34240. computeDepthSort = (options.depthSort) ? true : false;
  34241. distanceTo = (options.distanceTo);
  34242. if (computeDepthSort) {
  34243. if (distanceTo === undefined) {
  34244. distanceTo = BABYLON.Vector3.Zero();
  34245. }
  34246. var depthSortedFacets = options.depthSortedFacets;
  34247. }
  34248. }
  34249. // facetPartitioning reinit if needed
  34250. var xSubRatio = 0;
  34251. var ySubRatio = 0;
  34252. var zSubRatio = 0;
  34253. var subSq = 0;
  34254. if (computeFacetPartitioning && options && options.bbSize) {
  34255. var ox = 0; // X partitioning index for facet position
  34256. var oy = 0; // Y partinioning index for facet position
  34257. var oz = 0; // Z partinioning index for facet position
  34258. var b1x = 0; // X partitioning index for facet v1 vertex
  34259. var b1y = 0; // Y partitioning index for facet v1 vertex
  34260. var b1z = 0; // z partitioning index for facet v1 vertex
  34261. var b2x = 0; // X partitioning index for facet v2 vertex
  34262. var b2y = 0; // Y partitioning index for facet v2 vertex
  34263. var b2z = 0; // Z partitioning index for facet v2 vertex
  34264. var b3x = 0; // X partitioning index for facet v3 vertex
  34265. var b3y = 0; // Y partitioning index for facet v3 vertex
  34266. var b3z = 0; // Z partitioning index for facet v3 vertex
  34267. var block_idx_o = 0; // facet barycenter block index
  34268. var block_idx_v1 = 0; // v1 vertex block index
  34269. var block_idx_v2 = 0; // v2 vertex block index
  34270. var block_idx_v3 = 0; // v3 vertex block index
  34271. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34272. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34273. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34274. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34275. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34276. subSq = options.subDiv.max * options.subDiv.max;
  34277. options.facetPartitioning.length = 0;
  34278. }
  34279. // reset the normals
  34280. for (index = 0; index < positions.length; index++) {
  34281. normals[index] = 0.0;
  34282. }
  34283. // Loop : 1 indice triplet = 1 facet
  34284. var nbFaces = (indices.length / 3) | 0;
  34285. for (index = 0; index < nbFaces; index++) {
  34286. // get the indexes of the coordinates of each vertex of the facet
  34287. v1x = indices[index * 3] * 3;
  34288. v1y = v1x + 1;
  34289. v1z = v1x + 2;
  34290. v2x = indices[index * 3 + 1] * 3;
  34291. v2y = v2x + 1;
  34292. v2z = v2x + 2;
  34293. v3x = indices[index * 3 + 2] * 3;
  34294. v3y = v3x + 1;
  34295. v3z = v3x + 2;
  34296. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34297. p1p2y = positions[v1y] - positions[v2y];
  34298. p1p2z = positions[v1z] - positions[v2z];
  34299. p3p2x = positions[v3x] - positions[v2x];
  34300. p3p2y = positions[v3y] - positions[v2y];
  34301. p3p2z = positions[v3z] - positions[v2z];
  34302. // compute the face normal with the cross product
  34303. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34304. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34305. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34306. // normalize this normal and store it in the array facetData
  34307. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34308. length = (length === 0) ? 1.0 : length;
  34309. faceNormalx /= length;
  34310. faceNormaly /= length;
  34311. faceNormalz /= length;
  34312. if (computeFacetNormals && options) {
  34313. options.facetNormals[index].x = faceNormalx;
  34314. options.facetNormals[index].y = faceNormaly;
  34315. options.facetNormals[index].z = faceNormalz;
  34316. }
  34317. if (computeFacetPositions && options) {
  34318. // compute and the facet barycenter coordinates in the array facetPositions
  34319. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34320. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34321. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34322. }
  34323. if (computeFacetPartitioning && options) {
  34324. // store the facet indexes in arrays in the main facetPartitioning array :
  34325. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34326. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34327. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34328. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34329. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34330. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34331. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34332. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34333. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34334. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34335. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34336. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34337. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34338. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34339. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34340. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34341. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34342. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34343. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34344. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34345. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34346. // push each facet index in each block containing the vertex
  34347. options.facetPartitioning[block_idx_v1].push(index);
  34348. if (block_idx_v2 != block_idx_v1) {
  34349. options.facetPartitioning[block_idx_v2].push(index);
  34350. }
  34351. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34352. options.facetPartitioning[block_idx_v3].push(index);
  34353. }
  34354. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34355. options.facetPartitioning[block_idx_o].push(index);
  34356. }
  34357. }
  34358. if (computeDepthSort && options && options.facetPositions) {
  34359. var dsf = depthSortedFacets[index];
  34360. dsf.ind = index * 3;
  34361. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34362. }
  34363. // compute the normals anyway
  34364. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34365. normals[v1y] += faceNormaly;
  34366. normals[v1z] += faceNormalz;
  34367. normals[v2x] += faceNormalx;
  34368. normals[v2y] += faceNormaly;
  34369. normals[v2z] += faceNormalz;
  34370. normals[v3x] += faceNormalx;
  34371. normals[v3y] += faceNormaly;
  34372. normals[v3z] += faceNormalz;
  34373. }
  34374. // last normalization of each normal
  34375. for (index = 0; index < normals.length / 3; index++) {
  34376. faceNormalx = normals[index * 3];
  34377. faceNormaly = normals[index * 3 + 1];
  34378. faceNormalz = normals[index * 3 + 2];
  34379. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34380. length = (length === 0) ? 1.0 : length;
  34381. faceNormalx /= length;
  34382. faceNormaly /= length;
  34383. faceNormalz /= length;
  34384. normals[index * 3] = faceNormalx;
  34385. normals[index * 3 + 1] = faceNormaly;
  34386. normals[index * 3 + 2] = faceNormalz;
  34387. }
  34388. };
  34389. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34390. var li = indices.length;
  34391. var ln = normals.length;
  34392. var i;
  34393. var n;
  34394. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34395. switch (sideOrientation) {
  34396. case BABYLON.Mesh.FRONTSIDE:
  34397. // nothing changed
  34398. break;
  34399. case BABYLON.Mesh.BACKSIDE:
  34400. var tmp;
  34401. // indices
  34402. for (i = 0; i < li; i += 3) {
  34403. tmp = indices[i];
  34404. indices[i] = indices[i + 2];
  34405. indices[i + 2] = tmp;
  34406. }
  34407. // normals
  34408. for (n = 0; n < ln; n++) {
  34409. normals[n] = -normals[n];
  34410. }
  34411. break;
  34412. case BABYLON.Mesh.DOUBLESIDE:
  34413. // positions
  34414. var lp = positions.length;
  34415. var l = lp / 3;
  34416. for (var p = 0; p < lp; p++) {
  34417. positions[lp + p] = positions[p];
  34418. }
  34419. // indices
  34420. for (i = 0; i < li; i += 3) {
  34421. indices[i + li] = indices[i + 2] + l;
  34422. indices[i + 1 + li] = indices[i + 1] + l;
  34423. indices[i + 2 + li] = indices[i] + l;
  34424. }
  34425. // normals
  34426. for (n = 0; n < ln; n++) {
  34427. normals[ln + n] = -normals[n];
  34428. }
  34429. // uvs
  34430. var lu = uvs.length;
  34431. var u = 0;
  34432. for (u = 0; u < lu; u++) {
  34433. uvs[u + lu] = uvs[u];
  34434. }
  34435. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34436. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34437. u = 0;
  34438. for (i = 0; i < lu / 2; i++) {
  34439. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34440. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34441. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34442. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34443. u += 2;
  34444. }
  34445. break;
  34446. }
  34447. };
  34448. /**
  34449. * Creates a new VertexData from the imported parameters.
  34450. */
  34451. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34452. var vertexData = new VertexData();
  34453. // positions
  34454. var positions = parsedVertexData.positions;
  34455. if (positions) {
  34456. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34457. }
  34458. // normals
  34459. var normals = parsedVertexData.normals;
  34460. if (normals) {
  34461. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34462. }
  34463. // tangents
  34464. var tangents = parsedVertexData.tangents;
  34465. if (tangents) {
  34466. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34467. }
  34468. // uvs
  34469. var uvs = parsedVertexData.uvs;
  34470. if (uvs) {
  34471. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34472. }
  34473. // uv2s
  34474. var uv2s = parsedVertexData.uv2s;
  34475. if (uv2s) {
  34476. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34477. }
  34478. // uv3s
  34479. var uv3s = parsedVertexData.uv3s;
  34480. if (uv3s) {
  34481. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34482. }
  34483. // uv4s
  34484. var uv4s = parsedVertexData.uv4s;
  34485. if (uv4s) {
  34486. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34487. }
  34488. // uv5s
  34489. var uv5s = parsedVertexData.uv5s;
  34490. if (uv5s) {
  34491. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34492. }
  34493. // uv6s
  34494. var uv6s = parsedVertexData.uv6s;
  34495. if (uv6s) {
  34496. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34497. }
  34498. // colors
  34499. var colors = parsedVertexData.colors;
  34500. if (colors) {
  34501. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34502. }
  34503. // matricesIndices
  34504. var matricesIndices = parsedVertexData.matricesIndices;
  34505. if (matricesIndices) {
  34506. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34507. }
  34508. // matricesWeights
  34509. var matricesWeights = parsedVertexData.matricesWeights;
  34510. if (matricesWeights) {
  34511. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34512. }
  34513. // indices
  34514. var indices = parsedVertexData.indices;
  34515. if (indices) {
  34516. vertexData.indices = indices;
  34517. }
  34518. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34519. };
  34520. return VertexData;
  34521. }());
  34522. BABYLON.VertexData = VertexData;
  34523. })(BABYLON || (BABYLON = {}));
  34524. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34525. var BABYLON;
  34526. (function (BABYLON) {
  34527. /**
  34528. * Class used to store geometry data (vertex buffers + index buffer)
  34529. */
  34530. var Geometry = /** @class */ (function () {
  34531. /**
  34532. * Creates a new geometry
  34533. * @param id defines the unique ID
  34534. * @param scene defines the hosting scene
  34535. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34536. * @param updatable defines if geometry must be updatable (false by default)
  34537. * @param mesh defines the mesh that will be associated with the geometry
  34538. */
  34539. function Geometry(id, scene, vertexData, updatable, mesh) {
  34540. if (updatable === void 0) { updatable = false; }
  34541. if (mesh === void 0) { mesh = null; }
  34542. /**
  34543. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34544. */
  34545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34546. this._totalVertices = 0;
  34547. this._isDisposed = false;
  34548. this._indexBufferIsUpdatable = false;
  34549. this.id = id;
  34550. this._engine = scene.getEngine();
  34551. this._meshes = [];
  34552. this._scene = scene;
  34553. //Init vertex buffer cache
  34554. this._vertexBuffers = {};
  34555. this._indices = [];
  34556. this._updatable = updatable;
  34557. // vertexData
  34558. if (vertexData) {
  34559. this.setAllVerticesData(vertexData, updatable);
  34560. }
  34561. else {
  34562. this._totalVertices = 0;
  34563. this._indices = [];
  34564. }
  34565. if (this._engine.getCaps().vertexArrayObject) {
  34566. this._vertexArrayObjects = {};
  34567. }
  34568. // applyToMesh
  34569. if (mesh) {
  34570. if (mesh.getClassName() === "LinesMesh") {
  34571. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34572. this.updateExtend();
  34573. }
  34574. this.applyToMesh(mesh);
  34575. mesh.computeWorldMatrix(true);
  34576. }
  34577. }
  34578. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34579. /**
  34580. * 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
  34581. */
  34582. get: function () {
  34583. return this._boundingBias;
  34584. },
  34585. /**
  34586. * 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
  34587. */
  34588. set: function (value) {
  34589. if (this._boundingBias && this._boundingBias.equals(value)) {
  34590. return;
  34591. }
  34592. this._boundingBias = value.clone();
  34593. this.updateBoundingInfo(true, null);
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. /**
  34599. * Static function used to attach a new empty geometry to a mesh
  34600. * @param mesh defines the mesh to attach the geometry to
  34601. * @returns the new {BABYLON.Geometry}
  34602. */
  34603. Geometry.CreateGeometryForMesh = function (mesh) {
  34604. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34605. geometry.applyToMesh(mesh);
  34606. return geometry;
  34607. };
  34608. Object.defineProperty(Geometry.prototype, "extend", {
  34609. /**
  34610. * Gets the current extend of the geometry
  34611. */
  34612. get: function () {
  34613. return this._extend;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. /**
  34619. * Gets the hosting scene
  34620. * @returns the hosting {BABYLON.Scene}
  34621. */
  34622. Geometry.prototype.getScene = function () {
  34623. return this._scene;
  34624. };
  34625. /**
  34626. * Gets the hosting engine
  34627. * @returns the hosting {BABYLON.Engine}
  34628. */
  34629. Geometry.prototype.getEngine = function () {
  34630. return this._engine;
  34631. };
  34632. /**
  34633. * Defines if the geometry is ready to use
  34634. * @returns true if the geometry is ready to be used
  34635. */
  34636. Geometry.prototype.isReady = function () {
  34637. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34638. };
  34639. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34640. /**
  34641. * Gets a value indicating that the geometry should not be serialized
  34642. */
  34643. get: function () {
  34644. for (var index = 0; index < this._meshes.length; index++) {
  34645. if (!this._meshes[index].doNotSerialize) {
  34646. return false;
  34647. }
  34648. }
  34649. return true;
  34650. },
  34651. enumerable: true,
  34652. configurable: true
  34653. });
  34654. /** @ignore */
  34655. Geometry.prototype._rebuild = function () {
  34656. if (this._vertexArrayObjects) {
  34657. this._vertexArrayObjects = {};
  34658. }
  34659. // Index buffer
  34660. if (this._meshes.length !== 0 && this._indices) {
  34661. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34662. }
  34663. // Vertex buffers
  34664. for (var key in this._vertexBuffers) {
  34665. var vertexBuffer = this._vertexBuffers[key];
  34666. vertexBuffer._rebuild();
  34667. }
  34668. };
  34669. /**
  34670. * Affects all gemetry data in one call
  34671. * @param vertexData defines the geometry data
  34672. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34673. */
  34674. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34675. vertexData.applyToGeometry(this, updatable);
  34676. this.notifyUpdate();
  34677. };
  34678. /**
  34679. * Set specific vertex data
  34680. * @param kind defines the data kind (Position, normal, etc...)
  34681. * @param data defines the vertex data to use
  34682. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34683. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34684. */
  34685. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34686. if (updatable === void 0) { updatable = false; }
  34687. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34688. this.setVerticesBuffer(buffer);
  34689. };
  34690. /**
  34691. * Removes a specific vertex data
  34692. * @param kind defines the data kind (Position, normal, etc...)
  34693. */
  34694. Geometry.prototype.removeVerticesData = function (kind) {
  34695. if (this._vertexBuffers[kind]) {
  34696. this._vertexBuffers[kind].dispose();
  34697. delete this._vertexBuffers[kind];
  34698. }
  34699. };
  34700. /**
  34701. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34702. * @param buffer defines the vertex buffer to use
  34703. */
  34704. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34705. var kind = buffer.getKind();
  34706. if (this._vertexBuffers[kind]) {
  34707. this._vertexBuffers[kind].dispose();
  34708. }
  34709. this._vertexBuffers[kind] = buffer;
  34710. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34711. var data = buffer.getData();
  34712. var stride = buffer.getStrideSize();
  34713. this._totalVertices = data.length / stride;
  34714. this.updateExtend(data, stride);
  34715. this._resetPointsArrayCache();
  34716. var meshes = this._meshes;
  34717. var numOfMeshes = meshes.length;
  34718. for (var index = 0; index < numOfMeshes; index++) {
  34719. var mesh = meshes[index];
  34720. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34721. mesh._createGlobalSubMesh(false);
  34722. mesh.computeWorldMatrix(true);
  34723. }
  34724. }
  34725. this.notifyUpdate(kind);
  34726. if (this._vertexArrayObjects) {
  34727. this._disposeVertexArrayObjects();
  34728. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34729. }
  34730. };
  34731. /**
  34732. * Update a specific vertex buffer
  34733. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34734. * It will do nothing if the buffer is not updatable
  34735. * @param kind defines the data kind (Position, normal, etc...)
  34736. * @param data defines the data to use
  34737. * @param offset defines the offset in the target buffer where to store the data
  34738. */
  34739. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34740. var vertexBuffer = this.getVertexBuffer(kind);
  34741. if (!vertexBuffer) {
  34742. return;
  34743. }
  34744. vertexBuffer.updateDirectly(data, offset);
  34745. this.notifyUpdate(kind);
  34746. };
  34747. /**
  34748. * Update a specific vertex buffer
  34749. * This function will create a new buffer if the current one is not updatable
  34750. * @param kind defines the data kind (Position, normal, etc...)
  34751. * @param data defines the data to use
  34752. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34753. */
  34754. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34755. if (updateExtends === void 0) { updateExtends = false; }
  34756. var vertexBuffer = this.getVertexBuffer(kind);
  34757. if (!vertexBuffer) {
  34758. return;
  34759. }
  34760. vertexBuffer.update(data);
  34761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34762. var stride = vertexBuffer.getStrideSize();
  34763. this._totalVertices = data.length / stride;
  34764. this.updateBoundingInfo(updateExtends, data);
  34765. }
  34766. this.notifyUpdate(kind);
  34767. };
  34768. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34769. if (updateExtends) {
  34770. this.updateExtend(data);
  34771. }
  34772. var meshes = this._meshes;
  34773. var numOfMeshes = meshes.length;
  34774. this._resetPointsArrayCache();
  34775. for (var index = 0; index < numOfMeshes; index++) {
  34776. var mesh = meshes[index];
  34777. if (updateExtends) {
  34778. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34779. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34780. var subMesh = mesh.subMeshes[subIndex];
  34781. subMesh.refreshBoundingInfo();
  34782. }
  34783. }
  34784. }
  34785. };
  34786. /** @ignore */
  34787. Geometry.prototype._bind = function (effect, indexToBind) {
  34788. if (!effect) {
  34789. return;
  34790. }
  34791. if (indexToBind === undefined) {
  34792. indexToBind = this._indexBuffer;
  34793. }
  34794. var vbs = this.getVertexBuffers();
  34795. if (!vbs) {
  34796. return;
  34797. }
  34798. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34799. this._engine.bindBuffers(vbs, indexToBind, effect);
  34800. return;
  34801. }
  34802. // Using VAO
  34803. if (!this._vertexArrayObjects[effect.key]) {
  34804. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34805. }
  34806. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34807. };
  34808. /**
  34809. * Gets total number of vertices
  34810. * @returns the total number of vertices
  34811. */
  34812. Geometry.prototype.getTotalVertices = function () {
  34813. if (!this.isReady()) {
  34814. return 0;
  34815. }
  34816. return this._totalVertices;
  34817. };
  34818. /**
  34819. * Gets a specific vertex data attached to this geometry
  34820. * @param kind defines the data kind (Position, normal, etc...)
  34821. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34822. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34823. * @returns a float array containing vertex data
  34824. */
  34825. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34826. var vertexBuffer = this.getVertexBuffer(kind);
  34827. if (!vertexBuffer) {
  34828. return null;
  34829. }
  34830. var orig = vertexBuffer.getData();
  34831. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34832. return orig;
  34833. }
  34834. else {
  34835. var len = orig.length;
  34836. var copy = [];
  34837. for (var i = 0; i < len; i++) {
  34838. copy.push(orig[i]);
  34839. }
  34840. return copy;
  34841. }
  34842. };
  34843. /**
  34844. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34845. * @param kind defines the data kind (Position, normal, etc...)
  34846. * @returns true if the vertex buffer with the specified kind is updatable
  34847. */
  34848. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34849. var vb = this._vertexBuffers[kind];
  34850. if (!vb) {
  34851. return false;
  34852. }
  34853. return vb.isUpdatable();
  34854. };
  34855. /**
  34856. * Gets a specific vertex buffer
  34857. * @param kind defines the data kind (Position, normal, etc...)
  34858. * @returns a {BABYLON.VertexBuffer}
  34859. */
  34860. Geometry.prototype.getVertexBuffer = function (kind) {
  34861. if (!this.isReady()) {
  34862. return null;
  34863. }
  34864. return this._vertexBuffers[kind];
  34865. };
  34866. /**
  34867. * Returns all vertex buffers
  34868. * @return an object holding all vertex buffers indexed by kind
  34869. */
  34870. Geometry.prototype.getVertexBuffers = function () {
  34871. if (!this.isReady()) {
  34872. return null;
  34873. }
  34874. return this._vertexBuffers;
  34875. };
  34876. /**
  34877. * Gets a boolean indicating if specific vertex buffer is present
  34878. * @param kind defines the data kind (Position, normal, etc...)
  34879. * @returns true if data is present
  34880. */
  34881. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34882. if (!this._vertexBuffers) {
  34883. if (this._delayInfo) {
  34884. return this._delayInfo.indexOf(kind) !== -1;
  34885. }
  34886. return false;
  34887. }
  34888. return this._vertexBuffers[kind] !== undefined;
  34889. };
  34890. /**
  34891. * Gets a list of all attached data kinds (Position, normal, etc...)
  34892. * @returns a list of string containing all kinds
  34893. */
  34894. Geometry.prototype.getVerticesDataKinds = function () {
  34895. var result = [];
  34896. var kind;
  34897. if (!this._vertexBuffers && this._delayInfo) {
  34898. for (kind in this._delayInfo) {
  34899. result.push(kind);
  34900. }
  34901. }
  34902. else {
  34903. for (kind in this._vertexBuffers) {
  34904. result.push(kind);
  34905. }
  34906. }
  34907. return result;
  34908. };
  34909. /**
  34910. * Update index buffer
  34911. * @param indices defines the indices to store in the index buffer
  34912. * @param offset defines the offset in the target buffer where to store the data
  34913. */
  34914. Geometry.prototype.updateIndices = function (indices, offset) {
  34915. if (!this._indexBuffer) {
  34916. return;
  34917. }
  34918. if (!this._indexBufferIsUpdatable) {
  34919. this.setIndices(indices, null, true);
  34920. }
  34921. else {
  34922. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34923. }
  34924. };
  34925. /**
  34926. * Creates a new index buffer
  34927. * @param indices defines the indices to store in the index buffer
  34928. * @param totalVertices defines the total number of vertices (could be null)
  34929. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34930. */
  34931. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34932. if (totalVertices === void 0) { totalVertices = null; }
  34933. if (updatable === void 0) { updatable = false; }
  34934. if (this._indexBuffer) {
  34935. this._engine._releaseBuffer(this._indexBuffer);
  34936. }
  34937. this._disposeVertexArrayObjects();
  34938. this._indices = indices;
  34939. this._indexBufferIsUpdatable = updatable;
  34940. if (this._meshes.length !== 0 && this._indices) {
  34941. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34942. }
  34943. if (totalVertices != undefined) {
  34944. this._totalVertices = totalVertices;
  34945. }
  34946. var meshes = this._meshes;
  34947. var numOfMeshes = meshes.length;
  34948. for (var index = 0; index < numOfMeshes; index++) {
  34949. meshes[index]._createGlobalSubMesh(true);
  34950. }
  34951. this.notifyUpdate();
  34952. };
  34953. /**
  34954. * Return the total number of indices
  34955. * @returns the total number of indices
  34956. */
  34957. Geometry.prototype.getTotalIndices = function () {
  34958. if (!this.isReady()) {
  34959. return 0;
  34960. }
  34961. return this._indices.length;
  34962. };
  34963. /**
  34964. * Gets the index buffer array
  34965. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34966. * @returns the index buffer array
  34967. */
  34968. Geometry.prototype.getIndices = function (copyWhenShared) {
  34969. if (!this.isReady()) {
  34970. return null;
  34971. }
  34972. var orig = this._indices;
  34973. if (!copyWhenShared || this._meshes.length === 1) {
  34974. return orig;
  34975. }
  34976. else {
  34977. var len = orig.length;
  34978. var copy = [];
  34979. for (var i = 0; i < len; i++) {
  34980. copy.push(orig[i]);
  34981. }
  34982. return copy;
  34983. }
  34984. };
  34985. /**
  34986. * Gets the index buffer
  34987. * @return the index buffer
  34988. */
  34989. Geometry.prototype.getIndexBuffer = function () {
  34990. if (!this.isReady()) {
  34991. return null;
  34992. }
  34993. return this._indexBuffer;
  34994. };
  34995. /** @ignore */
  34996. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34997. if (effect === void 0) { effect = null; }
  34998. if (!effect || !this._vertexArrayObjects) {
  34999. return;
  35000. }
  35001. if (this._vertexArrayObjects[effect.key]) {
  35002. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35003. delete this._vertexArrayObjects[effect.key];
  35004. }
  35005. };
  35006. /**
  35007. * Release the associated resources for a specific mesh
  35008. * @param mesh defines the source mesh
  35009. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35010. */
  35011. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35012. var meshes = this._meshes;
  35013. var index = meshes.indexOf(mesh);
  35014. if (index === -1) {
  35015. return;
  35016. }
  35017. meshes.splice(index, 1);
  35018. mesh._geometry = null;
  35019. if (meshes.length === 0 && shouldDispose) {
  35020. this.dispose();
  35021. }
  35022. };
  35023. /**
  35024. * Apply current geometry to a given mesh
  35025. * @param mesh defines the mesh to apply geometry to
  35026. */
  35027. Geometry.prototype.applyToMesh = function (mesh) {
  35028. if (mesh._geometry === this) {
  35029. return;
  35030. }
  35031. var previousGeometry = mesh._geometry;
  35032. if (previousGeometry) {
  35033. previousGeometry.releaseForMesh(mesh);
  35034. }
  35035. var meshes = this._meshes;
  35036. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35037. mesh._geometry = this;
  35038. this._scene.pushGeometry(this);
  35039. meshes.push(mesh);
  35040. if (this.isReady()) {
  35041. this._applyToMesh(mesh);
  35042. }
  35043. else {
  35044. mesh._boundingInfo = this._boundingInfo;
  35045. }
  35046. };
  35047. Geometry.prototype.updateExtend = function (data, stride) {
  35048. if (data === void 0) { data = null; }
  35049. if (!data) {
  35050. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35051. }
  35052. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35053. };
  35054. Geometry.prototype._applyToMesh = function (mesh) {
  35055. var numOfMeshes = this._meshes.length;
  35056. // vertexBuffers
  35057. for (var kind in this._vertexBuffers) {
  35058. if (numOfMeshes === 1) {
  35059. this._vertexBuffers[kind].create();
  35060. }
  35061. var buffer = this._vertexBuffers[kind].getBuffer();
  35062. if (buffer)
  35063. buffer.references = numOfMeshes;
  35064. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35065. if (!this._extend) {
  35066. this.updateExtend(this._vertexBuffers[kind].getData());
  35067. }
  35068. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35069. mesh._createGlobalSubMesh(false);
  35070. //bounding info was just created again, world matrix should be applied again.
  35071. mesh._updateBoundingInfo();
  35072. }
  35073. }
  35074. // indexBuffer
  35075. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35076. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35077. }
  35078. if (this._indexBuffer) {
  35079. this._indexBuffer.references = numOfMeshes;
  35080. }
  35081. };
  35082. Geometry.prototype.notifyUpdate = function (kind) {
  35083. if (this.onGeometryUpdated) {
  35084. this.onGeometryUpdated(this, kind);
  35085. }
  35086. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35087. var mesh = _a[_i];
  35088. mesh._markSubMeshesAsAttributesDirty();
  35089. }
  35090. };
  35091. /**
  35092. * Load the geometry if it was flagged as delay loaded
  35093. * @param scene defines the hosting scene
  35094. * @param onLoaded defines a callback called when the geometry is loaded
  35095. */
  35096. Geometry.prototype.load = function (scene, onLoaded) {
  35097. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35098. return;
  35099. }
  35100. if (this.isReady()) {
  35101. if (onLoaded) {
  35102. onLoaded();
  35103. }
  35104. return;
  35105. }
  35106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35107. this._queueLoad(scene, onLoaded);
  35108. };
  35109. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35110. var _this = this;
  35111. if (!this.delayLoadingFile) {
  35112. return;
  35113. }
  35114. scene._addPendingData(this);
  35115. scene._loadFile(this.delayLoadingFile, function (data) {
  35116. if (!_this._delayLoadingFunction) {
  35117. return;
  35118. }
  35119. _this._delayLoadingFunction(JSON.parse(data), _this);
  35120. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35121. _this._delayInfo = [];
  35122. scene._removePendingData(_this);
  35123. var meshes = _this._meshes;
  35124. var numOfMeshes = meshes.length;
  35125. for (var index = 0; index < numOfMeshes; index++) {
  35126. _this._applyToMesh(meshes[index]);
  35127. }
  35128. if (onLoaded) {
  35129. onLoaded();
  35130. }
  35131. }, undefined, true);
  35132. };
  35133. /**
  35134. * Invert the geometry to move from a right handed system to a left handed one.
  35135. */
  35136. Geometry.prototype.toLeftHanded = function () {
  35137. // Flip faces
  35138. var tIndices = this.getIndices(false);
  35139. if (tIndices != null && tIndices.length > 0) {
  35140. for (var i = 0; i < tIndices.length; i += 3) {
  35141. var tTemp = tIndices[i + 0];
  35142. tIndices[i + 0] = tIndices[i + 2];
  35143. tIndices[i + 2] = tTemp;
  35144. }
  35145. this.setIndices(tIndices);
  35146. }
  35147. // Negate position.z
  35148. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35149. if (tPositions != null && tPositions.length > 0) {
  35150. for (var i = 0; i < tPositions.length; i += 3) {
  35151. tPositions[i + 2] = -tPositions[i + 2];
  35152. }
  35153. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35154. }
  35155. // Negate normal.z
  35156. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35157. if (tNormals != null && tNormals.length > 0) {
  35158. for (var i = 0; i < tNormals.length; i += 3) {
  35159. tNormals[i + 2] = -tNormals[i + 2];
  35160. }
  35161. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35162. }
  35163. };
  35164. // Cache
  35165. /** @ignore */
  35166. Geometry.prototype._resetPointsArrayCache = function () {
  35167. this._positions = null;
  35168. };
  35169. /** @ignore */
  35170. Geometry.prototype._generatePointsArray = function () {
  35171. if (this._positions)
  35172. return true;
  35173. this._positions = [];
  35174. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35175. if (!data) {
  35176. return false;
  35177. }
  35178. for (var index = 0; index < data.length; index += 3) {
  35179. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35180. }
  35181. return true;
  35182. };
  35183. /**
  35184. * Gets a value indicating if the geometry is disposed
  35185. * @returns true if the geometry was disposed
  35186. */
  35187. Geometry.prototype.isDisposed = function () {
  35188. return this._isDisposed;
  35189. };
  35190. Geometry.prototype._disposeVertexArrayObjects = function () {
  35191. if (this._vertexArrayObjects) {
  35192. for (var kind in this._vertexArrayObjects) {
  35193. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35194. }
  35195. this._vertexArrayObjects = {};
  35196. }
  35197. };
  35198. /**
  35199. * Free all associated resources
  35200. */
  35201. Geometry.prototype.dispose = function () {
  35202. var meshes = this._meshes;
  35203. var numOfMeshes = meshes.length;
  35204. var index;
  35205. for (index = 0; index < numOfMeshes; index++) {
  35206. this.releaseForMesh(meshes[index]);
  35207. }
  35208. this._meshes = [];
  35209. this._disposeVertexArrayObjects();
  35210. for (var kind in this._vertexBuffers) {
  35211. this._vertexBuffers[kind].dispose();
  35212. }
  35213. this._vertexBuffers = {};
  35214. this._totalVertices = 0;
  35215. if (this._indexBuffer) {
  35216. this._engine._releaseBuffer(this._indexBuffer);
  35217. }
  35218. this._indexBuffer = null;
  35219. this._indices = [];
  35220. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35221. this.delayLoadingFile = null;
  35222. this._delayLoadingFunction = null;
  35223. this._delayInfo = [];
  35224. this._boundingInfo = null;
  35225. this._scene.removeGeometry(this);
  35226. this._isDisposed = true;
  35227. };
  35228. /**
  35229. * Clone the current geometry into a new geometry
  35230. * @param id defines the unique ID of the new geometry
  35231. * @returns a new geometry object
  35232. */
  35233. Geometry.prototype.copy = function (id) {
  35234. var vertexData = new BABYLON.VertexData();
  35235. vertexData.indices = [];
  35236. var indices = this.getIndices();
  35237. if (indices) {
  35238. for (var index = 0; index < indices.length; index++) {
  35239. vertexData.indices.push(indices[index]);
  35240. }
  35241. }
  35242. var updatable = false;
  35243. var stopChecking = false;
  35244. var kind;
  35245. for (kind in this._vertexBuffers) {
  35246. // using slice() to make a copy of the array and not just reference it
  35247. var data = this.getVerticesData(kind);
  35248. if (data instanceof Float32Array) {
  35249. vertexData.set(new Float32Array(data), kind);
  35250. }
  35251. else {
  35252. vertexData.set(data.slice(0), kind);
  35253. }
  35254. if (!stopChecking) {
  35255. var vb = this.getVertexBuffer(kind);
  35256. if (vb) {
  35257. updatable = vb.isUpdatable();
  35258. stopChecking = !updatable;
  35259. }
  35260. }
  35261. }
  35262. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35263. geometry.delayLoadState = this.delayLoadState;
  35264. geometry.delayLoadingFile = this.delayLoadingFile;
  35265. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35266. for (kind in this._delayInfo) {
  35267. geometry._delayInfo = geometry._delayInfo || [];
  35268. geometry._delayInfo.push(kind);
  35269. }
  35270. // Bounding info
  35271. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35272. return geometry;
  35273. };
  35274. /**
  35275. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35276. * @return a JSON representation of the current geometry data (without the vertices data)
  35277. */
  35278. Geometry.prototype.serialize = function () {
  35279. var serializationObject = {};
  35280. serializationObject.id = this.id;
  35281. serializationObject.updatable = this._updatable;
  35282. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35283. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35284. }
  35285. return serializationObject;
  35286. };
  35287. Geometry.prototype.toNumberArray = function (origin) {
  35288. if (Array.isArray(origin)) {
  35289. return origin;
  35290. }
  35291. else {
  35292. return Array.prototype.slice.call(origin);
  35293. }
  35294. };
  35295. /**
  35296. * Serialize all vertices data into a JSON oject
  35297. * @returns a JSON representation of the current geometry data
  35298. */
  35299. Geometry.prototype.serializeVerticeData = function () {
  35300. var serializationObject = this.serialize();
  35301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35302. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35303. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35304. serializationObject.positions._updatable = true;
  35305. }
  35306. }
  35307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35308. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35309. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35310. serializationObject.normals._updatable = true;
  35311. }
  35312. }
  35313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35314. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35315. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35316. serializationObject.tangets._updatable = true;
  35317. }
  35318. }
  35319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35320. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35321. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35322. serializationObject.uvs._updatable = true;
  35323. }
  35324. }
  35325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35326. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35327. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35328. serializationObject.uv2s._updatable = true;
  35329. }
  35330. }
  35331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35332. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35333. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35334. serializationObject.uv3s._updatable = true;
  35335. }
  35336. }
  35337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35338. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35340. serializationObject.uv4s._updatable = true;
  35341. }
  35342. }
  35343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35344. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35346. serializationObject.uv5s._updatable = true;
  35347. }
  35348. }
  35349. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35350. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35351. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35352. serializationObject.uv6s._updatable = true;
  35353. }
  35354. }
  35355. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35356. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35357. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35358. serializationObject.colors._updatable = true;
  35359. }
  35360. }
  35361. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35362. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35363. serializationObject.matricesIndices._isExpanded = true;
  35364. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35365. serializationObject.matricesIndices._updatable = true;
  35366. }
  35367. }
  35368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35369. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35371. serializationObject.matricesWeights._updatable = true;
  35372. }
  35373. }
  35374. serializationObject.indices = this.toNumberArray(this.getIndices());
  35375. return serializationObject;
  35376. };
  35377. // Statics
  35378. /**
  35379. * Extracts a clone of a mesh geometry
  35380. * @param mesh defines the source mesh
  35381. * @param id defines the unique ID of the new geometry object
  35382. * @returns the new geometry object
  35383. */
  35384. Geometry.ExtractFromMesh = function (mesh, id) {
  35385. var geometry = mesh._geometry;
  35386. if (!geometry) {
  35387. return null;
  35388. }
  35389. return geometry.copy(id);
  35390. };
  35391. /**
  35392. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35393. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35394. * Be aware Math.random() could cause collisions, but:
  35395. * "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"
  35396. * @returns a string containing a new GUID
  35397. */
  35398. Geometry.RandomId = function () {
  35399. return BABYLON.Tools.RandomId();
  35400. };
  35401. /** @ignore */
  35402. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35403. var scene = mesh.getScene();
  35404. // Geometry
  35405. var geometryId = parsedGeometry.geometryId;
  35406. if (geometryId) {
  35407. var geometry = scene.getGeometryByID(geometryId);
  35408. if (geometry) {
  35409. geometry.applyToMesh(mesh);
  35410. }
  35411. }
  35412. else if (parsedGeometry instanceof ArrayBuffer) {
  35413. var binaryInfo = mesh._binaryInfo;
  35414. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35415. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35416. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35417. }
  35418. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35419. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35420. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35421. }
  35422. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35423. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35424. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35425. }
  35426. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35427. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35428. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35429. }
  35430. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35431. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35433. }
  35434. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35435. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35436. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35437. }
  35438. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35439. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35440. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35441. }
  35442. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35443. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35444. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35445. }
  35446. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35447. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35448. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35449. }
  35450. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35451. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35452. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35453. }
  35454. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35455. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35457. }
  35458. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35459. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35461. }
  35462. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35463. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35464. mesh.setIndices(indicesData, null);
  35465. }
  35466. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35467. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35468. mesh.subMeshes = [];
  35469. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35470. var materialIndex = subMeshesData[(i * 5) + 0];
  35471. var verticesStart = subMeshesData[(i * 5) + 1];
  35472. var verticesCount = subMeshesData[(i * 5) + 2];
  35473. var indexStart = subMeshesData[(i * 5) + 3];
  35474. var indexCount = subMeshesData[(i * 5) + 4];
  35475. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35476. }
  35477. }
  35478. }
  35479. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35480. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35481. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35482. if (parsedGeometry.tangents) {
  35483. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35484. }
  35485. if (parsedGeometry.uvs) {
  35486. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35487. }
  35488. if (parsedGeometry.uvs2) {
  35489. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35490. }
  35491. if (parsedGeometry.uvs3) {
  35492. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35493. }
  35494. if (parsedGeometry.uvs4) {
  35495. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35496. }
  35497. if (parsedGeometry.uvs5) {
  35498. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35499. }
  35500. if (parsedGeometry.uvs6) {
  35501. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35502. }
  35503. if (parsedGeometry.colors) {
  35504. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35505. }
  35506. if (parsedGeometry.matricesIndices) {
  35507. if (!parsedGeometry.matricesIndices._isExpanded) {
  35508. var floatIndices = [];
  35509. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35510. var matricesIndex = parsedGeometry.matricesIndices[i];
  35511. floatIndices.push(matricesIndex & 0x000000FF);
  35512. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35513. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35514. floatIndices.push(matricesIndex >> 24);
  35515. }
  35516. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35517. }
  35518. else {
  35519. delete parsedGeometry.matricesIndices._isExpanded;
  35520. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35521. }
  35522. }
  35523. if (parsedGeometry.matricesIndicesExtra) {
  35524. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35525. var floatIndices = [];
  35526. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35527. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35528. floatIndices.push(matricesIndex & 0x000000FF);
  35529. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35530. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35531. floatIndices.push(matricesIndex >> 24);
  35532. }
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35534. }
  35535. else {
  35536. delete parsedGeometry.matricesIndices._isExpanded;
  35537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35538. }
  35539. }
  35540. if (parsedGeometry.matricesWeights) {
  35541. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35542. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35543. }
  35544. if (parsedGeometry.matricesWeightsExtra) {
  35545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35546. }
  35547. mesh.setIndices(parsedGeometry.indices, null);
  35548. }
  35549. // SubMeshes
  35550. if (parsedGeometry.subMeshes) {
  35551. mesh.subMeshes = [];
  35552. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35553. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35554. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35555. }
  35556. }
  35557. // Flat shading
  35558. if (mesh._shouldGenerateFlatShading) {
  35559. mesh.convertToFlatShadedMesh();
  35560. delete mesh._shouldGenerateFlatShading;
  35561. }
  35562. // Update
  35563. mesh.computeWorldMatrix(true);
  35564. // Octree
  35565. var sceneOctree = scene.selectionOctree;
  35566. if (sceneOctree !== undefined && sceneOctree !== null) {
  35567. sceneOctree.addMesh(mesh);
  35568. }
  35569. };
  35570. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35571. var epsilon = 1e-3;
  35572. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35573. return;
  35574. }
  35575. var noInfluenceBoneIndex = 0.0;
  35576. if (parsedGeometry.skeletonId > -1) {
  35577. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35578. if (!skeleton) {
  35579. return;
  35580. }
  35581. noInfluenceBoneIndex = skeleton.bones.length;
  35582. }
  35583. else {
  35584. return;
  35585. }
  35586. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35587. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35588. var matricesWeights = parsedGeometry.matricesWeights;
  35589. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35590. var influencers = parsedGeometry.numBoneInfluencer;
  35591. var size = matricesWeights.length;
  35592. for (var i = 0; i < size; i += 4) {
  35593. var weight = 0.0;
  35594. var firstZeroWeight = -1;
  35595. for (var j = 0; j < 4; j++) {
  35596. var w = matricesWeights[i + j];
  35597. weight += w;
  35598. if (w < epsilon && firstZeroWeight < 0) {
  35599. firstZeroWeight = j;
  35600. }
  35601. }
  35602. if (matricesWeightsExtra) {
  35603. for (var j = 0; j < 4; j++) {
  35604. var w = matricesWeightsExtra[i + j];
  35605. weight += w;
  35606. if (w < epsilon && firstZeroWeight < 0) {
  35607. firstZeroWeight = j + 4;
  35608. }
  35609. }
  35610. }
  35611. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35612. firstZeroWeight = influencers - 1;
  35613. }
  35614. if (weight > epsilon) {
  35615. var mweight = 1.0 / weight;
  35616. for (var j = 0; j < 4; j++) {
  35617. matricesWeights[i + j] *= mweight;
  35618. }
  35619. if (matricesWeightsExtra) {
  35620. for (var j = 0; j < 4; j++) {
  35621. matricesWeightsExtra[i + j] *= mweight;
  35622. }
  35623. }
  35624. }
  35625. else {
  35626. if (firstZeroWeight >= 4) {
  35627. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35628. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35629. }
  35630. else {
  35631. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35632. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35633. }
  35634. }
  35635. }
  35636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35637. if (parsedGeometry.matricesWeightsExtra) {
  35638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35639. }
  35640. };
  35641. /**
  35642. * Create a new geometry from persisted data (Using .babylon file format)
  35643. * @param parsedVertexData defines the persisted data
  35644. * @param scene defines the hosting scene
  35645. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35646. * @returns the new geometry object
  35647. */
  35648. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35649. if (scene.getGeometryByID(parsedVertexData.id)) {
  35650. return null; // null since geometry could be something else than a box...
  35651. }
  35652. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35653. if (BABYLON.Tags) {
  35654. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35655. }
  35656. if (parsedVertexData.delayLoadingFile) {
  35657. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35658. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35659. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35660. geometry._delayInfo = [];
  35661. if (parsedVertexData.hasUVs) {
  35662. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35663. }
  35664. if (parsedVertexData.hasUVs2) {
  35665. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35666. }
  35667. if (parsedVertexData.hasUVs3) {
  35668. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35669. }
  35670. if (parsedVertexData.hasUVs4) {
  35671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35672. }
  35673. if (parsedVertexData.hasUVs5) {
  35674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35675. }
  35676. if (parsedVertexData.hasUVs6) {
  35677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35678. }
  35679. if (parsedVertexData.hasColors) {
  35680. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35681. }
  35682. if (parsedVertexData.hasMatricesIndices) {
  35683. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35684. }
  35685. if (parsedVertexData.hasMatricesWeights) {
  35686. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35687. }
  35688. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35689. }
  35690. else {
  35691. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35692. }
  35693. scene.pushGeometry(geometry, true);
  35694. return geometry;
  35695. };
  35696. return Geometry;
  35697. }());
  35698. BABYLON.Geometry = Geometry;
  35699. // Primitives
  35700. /// Abstract class
  35701. /**
  35702. * Abstract class used to provide common services for all typed geometries
  35703. */
  35704. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35705. __extends(_PrimitiveGeometry, _super);
  35706. /**
  35707. * Creates a new typed geometry
  35708. * @param id defines the unique ID of the geometry
  35709. * @param scene defines the hosting scene
  35710. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35711. * @param mesh defines the hosting mesh (can be null)
  35712. */
  35713. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35714. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35715. if (mesh === void 0) { mesh = null; }
  35716. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35717. _this._canBeRegenerated = _canBeRegenerated;
  35718. _this._beingRegenerated = true;
  35719. _this.regenerate();
  35720. _this._beingRegenerated = false;
  35721. return _this;
  35722. }
  35723. /**
  35724. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35725. * @returns true if the geometry can be regenerated
  35726. */
  35727. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35728. return this._canBeRegenerated;
  35729. };
  35730. /**
  35731. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35732. */
  35733. _PrimitiveGeometry.prototype.regenerate = function () {
  35734. if (!this._canBeRegenerated) {
  35735. return;
  35736. }
  35737. this._beingRegenerated = true;
  35738. this.setAllVerticesData(this._regenerateVertexData(), false);
  35739. this._beingRegenerated = false;
  35740. };
  35741. /**
  35742. * Clone the geometry
  35743. * @param id defines the unique ID of the new geometry
  35744. * @returns the new geometry
  35745. */
  35746. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35747. return _super.prototype.copy.call(this, id);
  35748. };
  35749. // overrides
  35750. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35751. if (!this._beingRegenerated) {
  35752. return;
  35753. }
  35754. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35755. };
  35756. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35757. if (!this._beingRegenerated) {
  35758. return;
  35759. }
  35760. _super.prototype.setVerticesData.call(this, kind, data, false);
  35761. };
  35762. // to override
  35763. /** @ignore */
  35764. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35765. throw new Error("Abstract method");
  35766. };
  35767. _PrimitiveGeometry.prototype.copy = function (id) {
  35768. throw new Error("Must be overriden in sub-classes.");
  35769. };
  35770. _PrimitiveGeometry.prototype.serialize = function () {
  35771. var serializationObject = _super.prototype.serialize.call(this);
  35772. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35773. return serializationObject;
  35774. };
  35775. return _PrimitiveGeometry;
  35776. }(Geometry));
  35777. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35778. /**
  35779. * Creates a ribbon geometry
  35780. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35781. */
  35782. var RibbonGeometry = /** @class */ (function (_super) {
  35783. __extends(RibbonGeometry, _super);
  35784. /**
  35785. * Creates a ribbon geometry
  35786. * @param id defines the unique ID of the geometry
  35787. * @param scene defines the hosting scene
  35788. * @param pathArray defines the array of paths to use
  35789. * @param closeArray defines if the last path and the first path must be joined
  35790. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35791. * @param offset defines the offset between points
  35792. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35793. * @param mesh defines the hosting mesh (can be null)
  35794. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35795. */
  35796. function RibbonGeometry(id, scene,
  35797. /**
  35798. * Defines the array of paths to use
  35799. */
  35800. pathArray,
  35801. /**
  35802. * Defines if the last and first points of each path in your pathArray must be joined
  35803. */
  35804. closeArray,
  35805. /**
  35806. * Defines if the last and first points of each path in your pathArray must be joined
  35807. */
  35808. closePath,
  35809. /**
  35810. * Defines the offset between points
  35811. */
  35812. offset, canBeRegenerated, mesh,
  35813. /**
  35814. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35815. */
  35816. side) {
  35817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35819. _this.pathArray = pathArray;
  35820. _this.closeArray = closeArray;
  35821. _this.closePath = closePath;
  35822. _this.offset = offset;
  35823. _this.side = side;
  35824. return _this;
  35825. }
  35826. /** @ignore */
  35827. RibbonGeometry.prototype._regenerateVertexData = function () {
  35828. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35829. };
  35830. RibbonGeometry.prototype.copy = function (id) {
  35831. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35832. };
  35833. return RibbonGeometry;
  35834. }(_PrimitiveGeometry));
  35835. BABYLON.RibbonGeometry = RibbonGeometry;
  35836. /**
  35837. * Creates a box geometry
  35838. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35839. */
  35840. var BoxGeometry = /** @class */ (function (_super) {
  35841. __extends(BoxGeometry, _super);
  35842. /**
  35843. * Creates a box geometry
  35844. * @param id defines the unique ID of the geometry
  35845. * @param scene defines the hosting scene
  35846. * @param size defines the zise of the box (width, height and depth are the same)
  35847. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35848. * @param mesh defines the hosting mesh (can be null)
  35849. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35850. */
  35851. function BoxGeometry(id, scene,
  35852. /**
  35853. * Defines the zise of the box (width, height and depth are the same)
  35854. */
  35855. size, canBeRegenerated, mesh,
  35856. /**
  35857. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35858. */
  35859. side) {
  35860. if (mesh === void 0) { mesh = null; }
  35861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35862. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35863. _this.size = size;
  35864. _this.side = side;
  35865. return _this;
  35866. }
  35867. BoxGeometry.prototype._regenerateVertexData = function () {
  35868. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35869. };
  35870. BoxGeometry.prototype.copy = function (id) {
  35871. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35872. };
  35873. BoxGeometry.prototype.serialize = function () {
  35874. var serializationObject = _super.prototype.serialize.call(this);
  35875. serializationObject.size = this.size;
  35876. return serializationObject;
  35877. };
  35878. BoxGeometry.Parse = function (parsedBox, scene) {
  35879. if (scene.getGeometryByID(parsedBox.id)) {
  35880. return null; // null since geometry could be something else than a box...
  35881. }
  35882. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35883. if (BABYLON.Tags) {
  35884. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35885. }
  35886. scene.pushGeometry(box, true);
  35887. return box;
  35888. };
  35889. return BoxGeometry;
  35890. }(_PrimitiveGeometry));
  35891. BABYLON.BoxGeometry = BoxGeometry;
  35892. /**
  35893. * Creates a sphere geometry
  35894. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35895. */
  35896. var SphereGeometry = /** @class */ (function (_super) {
  35897. __extends(SphereGeometry, _super);
  35898. /**
  35899. * Create a new sphere geometry
  35900. * @param id defines the unique ID of the geometry
  35901. * @param scene defines the hosting scene
  35902. * @param segments defines the number of segments to use to create the sphere
  35903. * @param diameter defines the diameter of the sphere
  35904. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35905. * @param mesh defines the hosting mesh (can be null)
  35906. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35907. */
  35908. function SphereGeometry(id, scene,
  35909. /**
  35910. * Defines the number of segments to use to create the sphere
  35911. */
  35912. segments,
  35913. /**
  35914. * Defines the diameter of the sphere
  35915. */
  35916. diameter, canBeRegenerated, mesh,
  35917. /**
  35918. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35919. */
  35920. side) {
  35921. if (mesh === void 0) { mesh = null; }
  35922. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35923. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35924. _this.segments = segments;
  35925. _this.diameter = diameter;
  35926. _this.side = side;
  35927. return _this;
  35928. }
  35929. SphereGeometry.prototype._regenerateVertexData = function () {
  35930. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35931. };
  35932. SphereGeometry.prototype.copy = function (id) {
  35933. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35934. };
  35935. SphereGeometry.prototype.serialize = function () {
  35936. var serializationObject = _super.prototype.serialize.call(this);
  35937. serializationObject.segments = this.segments;
  35938. serializationObject.diameter = this.diameter;
  35939. return serializationObject;
  35940. };
  35941. SphereGeometry.Parse = function (parsedSphere, scene) {
  35942. if (scene.getGeometryByID(parsedSphere.id)) {
  35943. return null; // null since geometry could be something else than a sphere...
  35944. }
  35945. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35946. if (BABYLON.Tags) {
  35947. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35948. }
  35949. scene.pushGeometry(sphere, true);
  35950. return sphere;
  35951. };
  35952. return SphereGeometry;
  35953. }(_PrimitiveGeometry));
  35954. BABYLON.SphereGeometry = SphereGeometry;
  35955. /**
  35956. * Creates a disc geometry
  35957. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35958. */
  35959. var DiscGeometry = /** @class */ (function (_super) {
  35960. __extends(DiscGeometry, _super);
  35961. /**
  35962. * Creates a new disc geometry
  35963. * @param id defines the unique ID of the geometry
  35964. * @param scene defines the hosting scene
  35965. * @param radius defines the radius of the disc
  35966. * @param tessellation defines the tesselation factor to apply to the disc
  35967. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35968. * @param mesh defines the hosting mesh (can be null)
  35969. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35970. */
  35971. function DiscGeometry(id, scene,
  35972. /**
  35973. * Defines the radius of the disc
  35974. */
  35975. radius,
  35976. /**
  35977. * Defines the tesselation factor to apply to the disc
  35978. */
  35979. tessellation, canBeRegenerated, mesh,
  35980. /**
  35981. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35982. */
  35983. side) {
  35984. if (mesh === void 0) { mesh = null; }
  35985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35986. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35987. _this.radius = radius;
  35988. _this.tessellation = tessellation;
  35989. _this.side = side;
  35990. return _this;
  35991. }
  35992. DiscGeometry.prototype._regenerateVertexData = function () {
  35993. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35994. };
  35995. DiscGeometry.prototype.copy = function (id) {
  35996. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35997. };
  35998. return DiscGeometry;
  35999. }(_PrimitiveGeometry));
  36000. BABYLON.DiscGeometry = DiscGeometry;
  36001. /**
  36002. * Creates a new cylinder geometry
  36003. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36004. */
  36005. var CylinderGeometry = /** @class */ (function (_super) {
  36006. __extends(CylinderGeometry, _super);
  36007. /**
  36008. * Creates a new cylinder geometry
  36009. * @param id defines the unique ID of the geometry
  36010. * @param scene defines the hosting scene
  36011. * @param height defines the height of the cylinder
  36012. * @param diameterTop defines the diameter of the cylinder's top cap
  36013. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36014. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36015. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36016. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36017. * @param mesh defines the hosting mesh (can be null)
  36018. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36019. */
  36020. function CylinderGeometry(id, scene,
  36021. /**
  36022. * Defines the height of the cylinder
  36023. */
  36024. height,
  36025. /**
  36026. * Defines the diameter of the cylinder's top cap
  36027. */
  36028. diameterTop,
  36029. /**
  36030. * Defines the diameter of the cylinder's bottom cap
  36031. */
  36032. diameterBottom,
  36033. /**
  36034. * Defines the tessellation factor to apply to the cylinder
  36035. */
  36036. tessellation,
  36037. /**
  36038. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36039. */
  36040. subdivisions, canBeRegenerated, mesh,
  36041. /**
  36042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36043. */
  36044. side) {
  36045. if (subdivisions === void 0) { subdivisions = 1; }
  36046. if (mesh === void 0) { mesh = null; }
  36047. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36048. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36049. _this.height = height;
  36050. _this.diameterTop = diameterTop;
  36051. _this.diameterBottom = diameterBottom;
  36052. _this.tessellation = tessellation;
  36053. _this.subdivisions = subdivisions;
  36054. _this.side = side;
  36055. return _this;
  36056. }
  36057. CylinderGeometry.prototype._regenerateVertexData = function () {
  36058. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36059. };
  36060. CylinderGeometry.prototype.copy = function (id) {
  36061. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36062. };
  36063. CylinderGeometry.prototype.serialize = function () {
  36064. var serializationObject = _super.prototype.serialize.call(this);
  36065. serializationObject.height = this.height;
  36066. serializationObject.diameterTop = this.diameterTop;
  36067. serializationObject.diameterBottom = this.diameterBottom;
  36068. serializationObject.tessellation = this.tessellation;
  36069. return serializationObject;
  36070. };
  36071. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36072. if (scene.getGeometryByID(parsedCylinder.id)) {
  36073. return null; // null since geometry could be something else than a cylinder...
  36074. }
  36075. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36076. if (BABYLON.Tags) {
  36077. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36078. }
  36079. scene.pushGeometry(cylinder, true);
  36080. return cylinder;
  36081. };
  36082. return CylinderGeometry;
  36083. }(_PrimitiveGeometry));
  36084. BABYLON.CylinderGeometry = CylinderGeometry;
  36085. /**
  36086. * Creates a new torus geometry
  36087. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36088. */
  36089. var TorusGeometry = /** @class */ (function (_super) {
  36090. __extends(TorusGeometry, _super);
  36091. /**
  36092. * Creates a new torus geometry
  36093. * @param id defines the unique ID of the geometry
  36094. * @param scene defines the hosting scene
  36095. * @param diameter defines the diameter of the torus
  36096. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36097. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36098. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36099. * @param mesh defines the hosting mesh (can be null)
  36100. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36101. */
  36102. function TorusGeometry(id, scene,
  36103. /**
  36104. * Defines the diameter of the torus
  36105. */
  36106. diameter,
  36107. /**
  36108. * Defines the thickness of the torus (ie. internal diameter)
  36109. */
  36110. thickness,
  36111. /**
  36112. * Defines the tesselation factor to apply to the torus
  36113. */
  36114. tessellation, canBeRegenerated, mesh,
  36115. /**
  36116. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36117. */
  36118. side) {
  36119. if (mesh === void 0) { mesh = null; }
  36120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36122. _this.diameter = diameter;
  36123. _this.thickness = thickness;
  36124. _this.tessellation = tessellation;
  36125. _this.side = side;
  36126. return _this;
  36127. }
  36128. TorusGeometry.prototype._regenerateVertexData = function () {
  36129. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36130. };
  36131. TorusGeometry.prototype.copy = function (id) {
  36132. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36133. };
  36134. TorusGeometry.prototype.serialize = function () {
  36135. var serializationObject = _super.prototype.serialize.call(this);
  36136. serializationObject.diameter = this.diameter;
  36137. serializationObject.thickness = this.thickness;
  36138. serializationObject.tessellation = this.tessellation;
  36139. return serializationObject;
  36140. };
  36141. TorusGeometry.Parse = function (parsedTorus, scene) {
  36142. if (scene.getGeometryByID(parsedTorus.id)) {
  36143. return null; // null since geometry could be something else than a torus...
  36144. }
  36145. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36146. if (BABYLON.Tags) {
  36147. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36148. }
  36149. scene.pushGeometry(torus, true);
  36150. return torus;
  36151. };
  36152. return TorusGeometry;
  36153. }(_PrimitiveGeometry));
  36154. BABYLON.TorusGeometry = TorusGeometry;
  36155. /**
  36156. * Creates a new ground geometry
  36157. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36158. */
  36159. var GroundGeometry = /** @class */ (function (_super) {
  36160. __extends(GroundGeometry, _super);
  36161. /**
  36162. * Creates a new ground geometry
  36163. * @param id defines the unique ID of the geometry
  36164. * @param scene defines the hosting scene
  36165. * @param width defines the width of the ground
  36166. * @param height defines the height of the ground
  36167. * @param subdivisions defines the subdivisions to apply to the ground
  36168. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36169. * @param mesh defines the hosting mesh (can be null)
  36170. */
  36171. function GroundGeometry(id, scene,
  36172. /**
  36173. * Defines the width of the ground
  36174. */
  36175. width,
  36176. /**
  36177. * Defines the height of the ground
  36178. */
  36179. height,
  36180. /**
  36181. * Defines the subdivisions to apply to the ground
  36182. */
  36183. subdivisions, canBeRegenerated, mesh) {
  36184. if (mesh === void 0) { mesh = null; }
  36185. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36186. _this.width = width;
  36187. _this.height = height;
  36188. _this.subdivisions = subdivisions;
  36189. return _this;
  36190. }
  36191. GroundGeometry.prototype._regenerateVertexData = function () {
  36192. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36193. };
  36194. GroundGeometry.prototype.copy = function (id) {
  36195. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36196. };
  36197. GroundGeometry.prototype.serialize = function () {
  36198. var serializationObject = _super.prototype.serialize.call(this);
  36199. serializationObject.width = this.width;
  36200. serializationObject.height = this.height;
  36201. serializationObject.subdivisions = this.subdivisions;
  36202. return serializationObject;
  36203. };
  36204. GroundGeometry.Parse = function (parsedGround, scene) {
  36205. if (scene.getGeometryByID(parsedGround.id)) {
  36206. return null; // null since geometry could be something else than a ground...
  36207. }
  36208. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36209. if (BABYLON.Tags) {
  36210. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36211. }
  36212. scene.pushGeometry(ground, true);
  36213. return ground;
  36214. };
  36215. return GroundGeometry;
  36216. }(_PrimitiveGeometry));
  36217. BABYLON.GroundGeometry = GroundGeometry;
  36218. /**
  36219. * Creates a tiled ground geometry
  36220. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36221. */
  36222. var TiledGroundGeometry = /** @class */ (function (_super) {
  36223. __extends(TiledGroundGeometry, _super);
  36224. /**
  36225. * Creates a tiled ground geometry
  36226. * @param id defines the unique ID of the geometry
  36227. * @param scene defines the hosting scene
  36228. * @param xmin defines the minimum value on X axis
  36229. * @param zmin defines the minimum value on Z axis
  36230. * @param xmax defines the maximum value on X axis
  36231. * @param zmax defines the maximum value on Z axis
  36232. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36233. * @param precision defines the precision to use when computing the tiles
  36234. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36235. * @param mesh defines the hosting mesh (can be null)
  36236. */
  36237. function TiledGroundGeometry(id, scene,
  36238. /**
  36239. * Defines the minimum value on X axis
  36240. */
  36241. xmin,
  36242. /**
  36243. * Defines the minimum value on Z axis
  36244. */
  36245. zmin,
  36246. /**
  36247. * Defines the maximum value on X axis
  36248. */
  36249. xmax,
  36250. /**
  36251. * Defines the maximum value on Z axis
  36252. */
  36253. zmax,
  36254. /**
  36255. * Defines the subdivisions to apply to the ground
  36256. */
  36257. subdivisions,
  36258. /**
  36259. * Defines the precision to use when computing the tiles
  36260. */
  36261. precision, canBeRegenerated, mesh) {
  36262. if (mesh === void 0) { mesh = null; }
  36263. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36264. _this.xmin = xmin;
  36265. _this.zmin = zmin;
  36266. _this.xmax = xmax;
  36267. _this.zmax = zmax;
  36268. _this.subdivisions = subdivisions;
  36269. _this.precision = precision;
  36270. return _this;
  36271. }
  36272. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36273. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36274. };
  36275. TiledGroundGeometry.prototype.copy = function (id) {
  36276. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36277. };
  36278. return TiledGroundGeometry;
  36279. }(_PrimitiveGeometry));
  36280. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36281. /**
  36282. * Creates a plane geometry
  36283. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36284. */
  36285. var PlaneGeometry = /** @class */ (function (_super) {
  36286. __extends(PlaneGeometry, _super);
  36287. /**
  36288. * Creates a plane geometry
  36289. * @param id defines the unique ID of the geometry
  36290. * @param scene defines the hosting scene
  36291. * @param size defines the size of the plane (width === height)
  36292. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36293. * @param mesh defines the hosting mesh (can be null)
  36294. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36295. */
  36296. function PlaneGeometry(id, scene,
  36297. /**
  36298. * Defines the size of the plane (width === height)
  36299. */
  36300. size, canBeRegenerated, mesh,
  36301. /**
  36302. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36303. */
  36304. side) {
  36305. if (mesh === void 0) { mesh = null; }
  36306. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36308. _this.size = size;
  36309. _this.side = side;
  36310. return _this;
  36311. }
  36312. PlaneGeometry.prototype._regenerateVertexData = function () {
  36313. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36314. };
  36315. PlaneGeometry.prototype.copy = function (id) {
  36316. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36317. };
  36318. PlaneGeometry.prototype.serialize = function () {
  36319. var serializationObject = _super.prototype.serialize.call(this);
  36320. serializationObject.size = this.size;
  36321. return serializationObject;
  36322. };
  36323. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36324. if (scene.getGeometryByID(parsedPlane.id)) {
  36325. return null; // null since geometry could be something else than a ground...
  36326. }
  36327. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36328. if (BABYLON.Tags) {
  36329. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36330. }
  36331. scene.pushGeometry(plane, true);
  36332. return plane;
  36333. };
  36334. return PlaneGeometry;
  36335. }(_PrimitiveGeometry));
  36336. BABYLON.PlaneGeometry = PlaneGeometry;
  36337. /**
  36338. * Creates a torus knot geometry
  36339. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36340. */
  36341. var TorusKnotGeometry = /** @class */ (function (_super) {
  36342. __extends(TorusKnotGeometry, _super);
  36343. /**
  36344. * Creates a torus knot geometry
  36345. * @param id defines the unique ID of the geometry
  36346. * @param scene defines the hosting scene
  36347. * @param radius defines the radius of the torus knot
  36348. * @param tube defines the thickness of the torus knot tube
  36349. * @param radialSegments defines the number of radial segments
  36350. * @param tubularSegments defines the number of tubular segments
  36351. * @param p defines the first number of windings
  36352. * @param q defines the second number of windings
  36353. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36354. * @param mesh defines the hosting mesh (can be null)
  36355. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36356. */
  36357. function TorusKnotGeometry(id, scene,
  36358. /**
  36359. * Defines the radius of the torus knot
  36360. */
  36361. radius,
  36362. /**
  36363. * Defines the thickness of the torus knot tube
  36364. */
  36365. tube,
  36366. /**
  36367. * Defines the number of radial segments
  36368. */
  36369. radialSegments,
  36370. /**
  36371. * Defines the number of tubular segments
  36372. */
  36373. tubularSegments,
  36374. /**
  36375. * Defines the first number of windings
  36376. */
  36377. p,
  36378. /**
  36379. * Defines the second number of windings
  36380. */
  36381. q, canBeRegenerated, mesh,
  36382. /**
  36383. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36384. */
  36385. side) {
  36386. if (mesh === void 0) { mesh = null; }
  36387. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36388. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36389. _this.radius = radius;
  36390. _this.tube = tube;
  36391. _this.radialSegments = radialSegments;
  36392. _this.tubularSegments = tubularSegments;
  36393. _this.p = p;
  36394. _this.q = q;
  36395. _this.side = side;
  36396. return _this;
  36397. }
  36398. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36399. 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 });
  36400. };
  36401. TorusKnotGeometry.prototype.copy = function (id) {
  36402. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36403. };
  36404. TorusKnotGeometry.prototype.serialize = function () {
  36405. var serializationObject = _super.prototype.serialize.call(this);
  36406. serializationObject.radius = this.radius;
  36407. serializationObject.tube = this.tube;
  36408. serializationObject.radialSegments = this.radialSegments;
  36409. serializationObject.tubularSegments = this.tubularSegments;
  36410. serializationObject.p = this.p;
  36411. serializationObject.q = this.q;
  36412. return serializationObject;
  36413. };
  36414. ;
  36415. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36416. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36417. return null; // null since geometry could be something else than a ground...
  36418. }
  36419. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36420. if (BABYLON.Tags) {
  36421. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36422. }
  36423. scene.pushGeometry(torusKnot, true);
  36424. return torusKnot;
  36425. };
  36426. return TorusKnotGeometry;
  36427. }(_PrimitiveGeometry));
  36428. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36429. //}
  36430. })(BABYLON || (BABYLON = {}));
  36431. //# sourceMappingURL=babylon.geometry.js.map
  36432. var BABYLON;
  36433. (function (BABYLON) {
  36434. /**
  36435. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36436. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36437. */
  36438. var PostProcessManager = /** @class */ (function () {
  36439. /**
  36440. * Creates a new instance of @see PostProcess
  36441. * @param scene The scene that the post process is associated with.
  36442. */
  36443. function PostProcessManager(scene) {
  36444. this._vertexBuffers = {};
  36445. this._scene = scene;
  36446. }
  36447. PostProcessManager.prototype._prepareBuffers = function () {
  36448. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36449. return;
  36450. }
  36451. // VBO
  36452. var vertices = [];
  36453. vertices.push(1, 1);
  36454. vertices.push(-1, 1);
  36455. vertices.push(-1, -1);
  36456. vertices.push(1, -1);
  36457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36458. this._buildIndexBuffer();
  36459. };
  36460. PostProcessManager.prototype._buildIndexBuffer = function () {
  36461. // Indices
  36462. var indices = [];
  36463. indices.push(0);
  36464. indices.push(1);
  36465. indices.push(2);
  36466. indices.push(0);
  36467. indices.push(2);
  36468. indices.push(3);
  36469. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36470. };
  36471. /**
  36472. * Rebuilds the vertex buffers of the manager.
  36473. */
  36474. PostProcessManager.prototype._rebuild = function () {
  36475. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36476. if (!vb) {
  36477. return;
  36478. }
  36479. vb._rebuild();
  36480. this._buildIndexBuffer();
  36481. };
  36482. // Methods
  36483. /**
  36484. * Prepares a frame to be run through a post process.
  36485. * @param sourceTexture The input texture to the post procesess. (default: null)
  36486. * @param postProcesses An array of post processes to be run. (default: null)
  36487. * @returns True if the post processes were able to be run.
  36488. */
  36489. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36490. if (sourceTexture === void 0) { sourceTexture = null; }
  36491. if (postProcesses === void 0) { postProcesses = null; }
  36492. var camera = this._scene.activeCamera;
  36493. if (!camera) {
  36494. return false;
  36495. }
  36496. var postProcesses = postProcesses || camera._postProcesses;
  36497. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36498. return false;
  36499. }
  36500. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36501. return true;
  36502. };
  36503. /**
  36504. * Manually render a set of post processes to a texture.
  36505. * @param postProcesses An array of post processes to be run.
  36506. * @param targetTexture The target texture to render to.
  36507. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36508. */
  36509. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36510. if (targetTexture === void 0) { targetTexture = null; }
  36511. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36512. var engine = this._scene.getEngine();
  36513. for (var index = 0; index < postProcesses.length; index++) {
  36514. if (index < postProcesses.length - 1) {
  36515. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36516. }
  36517. else {
  36518. if (targetTexture) {
  36519. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36520. }
  36521. else {
  36522. engine.restoreDefaultFramebuffer();
  36523. }
  36524. }
  36525. var pp = postProcesses[index];
  36526. var effect = pp.apply();
  36527. if (effect) {
  36528. pp.onBeforeRenderObservable.notifyObservers(effect);
  36529. // VBOs
  36530. this._prepareBuffers();
  36531. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36532. // Draw order
  36533. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36534. pp.onAfterRenderObservable.notifyObservers(effect);
  36535. }
  36536. }
  36537. // Restore depth buffer
  36538. engine.setDepthBuffer(true);
  36539. engine.setDepthWrite(true);
  36540. };
  36541. /**
  36542. * Finalize the result of the output of the postprocesses.
  36543. * @param doNotPresent If true the result will not be displayed to the screen.
  36544. * @param targetTexture The target texture to render to.
  36545. * @param faceIndex The index of the face to bind the target texture to.
  36546. * @param postProcesses The array of post processes to render.
  36547. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36548. */
  36549. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36550. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36551. var camera = this._scene.activeCamera;
  36552. if (!camera) {
  36553. return;
  36554. }
  36555. postProcesses = postProcesses || camera._postProcesses;
  36556. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36557. return;
  36558. }
  36559. var engine = this._scene.getEngine();
  36560. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36561. if (index < len - 1) {
  36562. postProcesses[index + 1].activate(camera, targetTexture);
  36563. }
  36564. else {
  36565. if (targetTexture) {
  36566. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36567. }
  36568. else {
  36569. engine.restoreDefaultFramebuffer();
  36570. }
  36571. }
  36572. if (doNotPresent) {
  36573. break;
  36574. }
  36575. var pp = postProcesses[index];
  36576. var effect = pp.apply();
  36577. if (effect) {
  36578. pp.onBeforeRenderObservable.notifyObservers(effect);
  36579. // VBOs
  36580. this._prepareBuffers();
  36581. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36582. // Draw order
  36583. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36584. pp.onAfterRenderObservable.notifyObservers(effect);
  36585. }
  36586. }
  36587. // Restore states
  36588. engine.setDepthBuffer(true);
  36589. engine.setDepthWrite(true);
  36590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36591. };
  36592. /**
  36593. * Disposes of the post process manager.
  36594. */
  36595. PostProcessManager.prototype.dispose = function () {
  36596. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36597. if (buffer) {
  36598. buffer.dispose();
  36599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36600. }
  36601. if (this._indexBuffer) {
  36602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36603. this._indexBuffer = null;
  36604. }
  36605. };
  36606. return PostProcessManager;
  36607. }());
  36608. BABYLON.PostProcessManager = PostProcessManager;
  36609. })(BABYLON || (BABYLON = {}));
  36610. //# sourceMappingURL=babylon.postProcessManager.js.map
  36611. var BABYLON;
  36612. (function (BABYLON) {
  36613. /**
  36614. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36615. */
  36616. var PerformanceMonitor = /** @class */ (function () {
  36617. /**
  36618. * constructor
  36619. * @param frameSampleSize The number of samples required to saturate the sliding window
  36620. */
  36621. function PerformanceMonitor(frameSampleSize) {
  36622. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36623. this._enabled = true;
  36624. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36625. }
  36626. /**
  36627. * Samples current frame
  36628. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36629. */
  36630. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36631. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36632. if (!this._enabled)
  36633. return;
  36634. if (this._lastFrameTimeMs != null) {
  36635. var dt = timeMs - this._lastFrameTimeMs;
  36636. this._rollingFrameTime.add(dt);
  36637. }
  36638. this._lastFrameTimeMs = timeMs;
  36639. };
  36640. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36641. /**
  36642. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36643. * @return Average frame time in milliseconds
  36644. */
  36645. get: function () {
  36646. return this._rollingFrameTime.average;
  36647. },
  36648. enumerable: true,
  36649. configurable: true
  36650. });
  36651. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36652. /**
  36653. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36654. * @return Frame time variance in milliseconds squared
  36655. */
  36656. get: function () {
  36657. return this._rollingFrameTime.variance;
  36658. },
  36659. enumerable: true,
  36660. configurable: true
  36661. });
  36662. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36663. /**
  36664. * Returns the frame time of the most recent frame
  36665. * @return Frame time in milliseconds
  36666. */
  36667. get: function () {
  36668. return this._rollingFrameTime.history(0);
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36674. /**
  36675. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36676. * @return Framerate in frames per second
  36677. */
  36678. get: function () {
  36679. return 1000.0 / this._rollingFrameTime.average;
  36680. },
  36681. enumerable: true,
  36682. configurable: true
  36683. });
  36684. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36685. /**
  36686. * Returns the average framerate in frames per second using the most recent frame time
  36687. * @return Framerate in frames per second
  36688. */
  36689. get: function () {
  36690. var history = this._rollingFrameTime.history(0);
  36691. if (history === 0) {
  36692. return 0;
  36693. }
  36694. return 1000.0 / history;
  36695. },
  36696. enumerable: true,
  36697. configurable: true
  36698. });
  36699. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36700. /**
  36701. * Returns true if enough samples have been taken to completely fill the sliding window
  36702. * @return true if saturated
  36703. */
  36704. get: function () {
  36705. return this._rollingFrameTime.isSaturated();
  36706. },
  36707. enumerable: true,
  36708. configurable: true
  36709. });
  36710. /**
  36711. * Enables contributions to the sliding window sample set
  36712. */
  36713. PerformanceMonitor.prototype.enable = function () {
  36714. this._enabled = true;
  36715. };
  36716. /**
  36717. * Disables contributions to the sliding window sample set
  36718. * Samples will not be interpolated over the disabled period
  36719. */
  36720. PerformanceMonitor.prototype.disable = function () {
  36721. this._enabled = false;
  36722. //clear last sample to avoid interpolating over the disabled period when next enabled
  36723. this._lastFrameTimeMs = null;
  36724. };
  36725. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36726. /**
  36727. * Returns true if sampling is enabled
  36728. * @return true if enabled
  36729. */
  36730. get: function () {
  36731. return this._enabled;
  36732. },
  36733. enumerable: true,
  36734. configurable: true
  36735. });
  36736. /**
  36737. * Resets performance monitor
  36738. */
  36739. PerformanceMonitor.prototype.reset = function () {
  36740. //clear last sample to avoid interpolating over the disabled period when next enabled
  36741. this._lastFrameTimeMs = null;
  36742. //wipe record
  36743. this._rollingFrameTime.reset();
  36744. };
  36745. return PerformanceMonitor;
  36746. }());
  36747. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36748. /**
  36749. * RollingAverage
  36750. *
  36751. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36752. */
  36753. var RollingAverage = /** @class */ (function () {
  36754. /**
  36755. * constructor
  36756. * @param length The number of samples required to saturate the sliding window
  36757. */
  36758. function RollingAverage(length) {
  36759. this._samples = new Array(length);
  36760. this.reset();
  36761. }
  36762. /**
  36763. * Adds a sample to the sample set
  36764. * @param v The sample value
  36765. */
  36766. RollingAverage.prototype.add = function (v) {
  36767. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36768. var delta;
  36769. //we need to check if we've already wrapped round
  36770. if (this.isSaturated()) {
  36771. //remove bottom of stack from mean
  36772. var bottomValue = this._samples[this._pos];
  36773. delta = bottomValue - this.average;
  36774. this.average -= delta / (this._sampleCount - 1);
  36775. this._m2 -= delta * (bottomValue - this.average);
  36776. }
  36777. else {
  36778. this._sampleCount++;
  36779. }
  36780. //add new value to mean
  36781. delta = v - this.average;
  36782. this.average += delta / (this._sampleCount);
  36783. this._m2 += delta * (v - this.average);
  36784. //set the new variance
  36785. this.variance = this._m2 / (this._sampleCount - 1);
  36786. this._samples[this._pos] = v;
  36787. this._pos++;
  36788. this._pos %= this._samples.length; //positive wrap around
  36789. };
  36790. /**
  36791. * Returns previously added values or null if outside of history or outside the sliding window domain
  36792. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36793. * @return Value previously recorded with add() or null if outside of range
  36794. */
  36795. RollingAverage.prototype.history = function (i) {
  36796. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36797. return 0;
  36798. }
  36799. var i0 = this._wrapPosition(this._pos - 1.0);
  36800. return this._samples[this._wrapPosition(i0 - i)];
  36801. };
  36802. /**
  36803. * Returns true if enough samples have been taken to completely fill the sliding window
  36804. * @return true if sample-set saturated
  36805. */
  36806. RollingAverage.prototype.isSaturated = function () {
  36807. return this._sampleCount >= this._samples.length;
  36808. };
  36809. /**
  36810. * Resets the rolling average (equivalent to 0 samples taken so far)
  36811. */
  36812. RollingAverage.prototype.reset = function () {
  36813. this.average = 0;
  36814. this.variance = 0;
  36815. this._sampleCount = 0;
  36816. this._pos = 0;
  36817. this._m2 = 0;
  36818. };
  36819. /**
  36820. * Wraps a value around the sample range boundaries
  36821. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36822. * @return Wrapped position in sample range
  36823. */
  36824. RollingAverage.prototype._wrapPosition = function (i) {
  36825. var max = this._samples.length;
  36826. return ((i % max) + max) % max;
  36827. };
  36828. return RollingAverage;
  36829. }());
  36830. BABYLON.RollingAverage = RollingAverage;
  36831. })(BABYLON || (BABYLON = {}));
  36832. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36833. var BABYLON;
  36834. (function (BABYLON) {
  36835. /**
  36836. * This groups together the common properties used for image processing either in direct forward pass
  36837. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36838. * or not.
  36839. */
  36840. var ImageProcessingConfiguration = /** @class */ (function () {
  36841. function ImageProcessingConfiguration() {
  36842. /**
  36843. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36844. */
  36845. this.colorCurves = new BABYLON.ColorCurves();
  36846. this._colorCurvesEnabled = false;
  36847. this._colorGradingEnabled = false;
  36848. this._colorGradingWithGreenDepth = true;
  36849. this._colorGradingBGR = true;
  36850. this._exposure = 1.0;
  36851. this._toneMappingEnabled = false;
  36852. this._contrast = 1.0;
  36853. /**
  36854. * Vignette stretch size.
  36855. */
  36856. this.vignetteStretch = 0;
  36857. /**
  36858. * Vignette centre X Offset.
  36859. */
  36860. this.vignetteCentreX = 0;
  36861. /**
  36862. * Vignette centre Y Offset.
  36863. */
  36864. this.vignetteCentreY = 0;
  36865. /**
  36866. * Vignette weight or intensity of the vignette effect.
  36867. */
  36868. this.vignetteWeight = 1.5;
  36869. /**
  36870. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36871. * if vignetteEnabled is set to true.
  36872. */
  36873. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36874. /**
  36875. * Camera field of view used by the Vignette effect.
  36876. */
  36877. this.vignetteCameraFov = 0.5;
  36878. this._grainEnabled = false;
  36879. this._grainIntensity = 30;
  36880. this._grainAnimated = false;
  36881. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36882. this._vignetteEnabled = false;
  36883. this._applyByPostProcess = false;
  36884. this._isEnabled = true;
  36885. /**
  36886. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36887. * @type {BABYLON.Observable}
  36888. */
  36889. this.onUpdateParameters = new BABYLON.Observable();
  36890. }
  36891. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36892. /**
  36893. * Gets wether the color curves effect is enabled.
  36894. */
  36895. get: function () {
  36896. return this._colorCurvesEnabled;
  36897. },
  36898. /**
  36899. * Sets wether the color curves effect is enabled.
  36900. */
  36901. set: function (value) {
  36902. if (this._colorCurvesEnabled === value) {
  36903. return;
  36904. }
  36905. this._colorCurvesEnabled = value;
  36906. this._updateParameters();
  36907. },
  36908. enumerable: true,
  36909. configurable: true
  36910. });
  36911. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36912. /**
  36913. * Gets wether the color grading effect is enabled.
  36914. */
  36915. get: function () {
  36916. return this._colorGradingEnabled;
  36917. },
  36918. /**
  36919. * Sets wether the color grading effect is enabled.
  36920. */
  36921. set: function (value) {
  36922. if (this._colorGradingEnabled === value) {
  36923. return;
  36924. }
  36925. this._colorGradingEnabled = value;
  36926. this._updateParameters();
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36932. /**
  36933. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36934. */
  36935. get: function () {
  36936. return this._colorGradingWithGreenDepth;
  36937. },
  36938. /**
  36939. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36940. */
  36941. set: function (value) {
  36942. if (this._colorGradingWithGreenDepth === value) {
  36943. return;
  36944. }
  36945. this._colorGradingWithGreenDepth = value;
  36946. this._updateParameters();
  36947. },
  36948. enumerable: true,
  36949. configurable: true
  36950. });
  36951. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36952. /**
  36953. * Gets wether the color grading texture contains BGR values.
  36954. */
  36955. get: function () {
  36956. return this._colorGradingBGR;
  36957. },
  36958. /**
  36959. * Sets wether the color grading texture contains BGR values.
  36960. */
  36961. set: function (value) {
  36962. if (this._colorGradingBGR === value) {
  36963. return;
  36964. }
  36965. this._colorGradingBGR = value;
  36966. this._updateParameters();
  36967. },
  36968. enumerable: true,
  36969. configurable: true
  36970. });
  36971. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36972. /**
  36973. * Gets the Exposure used in the effect.
  36974. */
  36975. get: function () {
  36976. return this._exposure;
  36977. },
  36978. /**
  36979. * Sets the Exposure used in the effect.
  36980. */
  36981. set: function (value) {
  36982. if (this._exposure === value) {
  36983. return;
  36984. }
  36985. this._exposure = value;
  36986. this._updateParameters();
  36987. },
  36988. enumerable: true,
  36989. configurable: true
  36990. });
  36991. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36992. /**
  36993. * Gets wether the tone mapping effect is enabled.
  36994. */
  36995. get: function () {
  36996. return this._toneMappingEnabled;
  36997. },
  36998. /**
  36999. * Sets wether the tone mapping effect is enabled.
  37000. */
  37001. set: function (value) {
  37002. if (this._toneMappingEnabled === value) {
  37003. return;
  37004. }
  37005. this._toneMappingEnabled = value;
  37006. this._updateParameters();
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37012. /**
  37013. * Gets the contrast used in the effect.
  37014. */
  37015. get: function () {
  37016. return this._contrast;
  37017. },
  37018. /**
  37019. * Sets the contrast used in the effect.
  37020. */
  37021. set: function (value) {
  37022. if (this._contrast === value) {
  37023. return;
  37024. }
  37025. this._contrast = value;
  37026. this._updateParameters();
  37027. },
  37028. enumerable: true,
  37029. configurable: true
  37030. });
  37031. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37032. /**
  37033. * If the grain effect should be enabled.
  37034. */
  37035. get: function () {
  37036. return this._grainEnabled;
  37037. },
  37038. set: function (value) {
  37039. if (this._grainEnabled === value) {
  37040. return;
  37041. }
  37042. this._grainEnabled = value;
  37043. this._updateParameters();
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37049. /**
  37050. * Amount of grain to be applied by the grain effect.
  37051. */
  37052. get: function () {
  37053. return this._grainIntensity;
  37054. },
  37055. set: function (value) {
  37056. if (this._grainIntensity === value) {
  37057. return;
  37058. }
  37059. this._grainIntensity = value;
  37060. },
  37061. enumerable: true,
  37062. configurable: true
  37063. });
  37064. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37065. /**
  37066. * If the grain effect should be animated.
  37067. */
  37068. get: function () {
  37069. return this._grainAnimated;
  37070. },
  37071. set: function (value) {
  37072. if (this._grainAnimated === value) {
  37073. return;
  37074. }
  37075. this._grainAnimated = value;
  37076. this._updateParameters();
  37077. },
  37078. enumerable: true,
  37079. configurable: true
  37080. });
  37081. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37082. /**
  37083. * Gets the vignette blend mode allowing different kind of effect.
  37084. */
  37085. get: function () {
  37086. return this._vignetteBlendMode;
  37087. },
  37088. /**
  37089. * Sets the vignette blend mode allowing different kind of effect.
  37090. */
  37091. set: function (value) {
  37092. if (this._vignetteBlendMode === value) {
  37093. return;
  37094. }
  37095. this._vignetteBlendMode = value;
  37096. this._updateParameters();
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37102. /**
  37103. * Gets wether the vignette effect is enabled.
  37104. */
  37105. get: function () {
  37106. return this._vignetteEnabled;
  37107. },
  37108. /**
  37109. * Sets wether the vignette effect is enabled.
  37110. */
  37111. set: function (value) {
  37112. if (this._vignetteEnabled === value) {
  37113. return;
  37114. }
  37115. this._vignetteEnabled = value;
  37116. this._updateParameters();
  37117. },
  37118. enumerable: true,
  37119. configurable: true
  37120. });
  37121. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37122. /**
  37123. * Gets wether the image processing is applied through a post process or not.
  37124. */
  37125. get: function () {
  37126. return this._applyByPostProcess;
  37127. },
  37128. /**
  37129. * Sets wether the image processing is applied through a post process or not.
  37130. */
  37131. set: function (value) {
  37132. if (this._applyByPostProcess === value) {
  37133. return;
  37134. }
  37135. this._applyByPostProcess = value;
  37136. this._updateParameters();
  37137. },
  37138. enumerable: true,
  37139. configurable: true
  37140. });
  37141. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37142. /**
  37143. * Gets wether the image processing is enabled or not.
  37144. */
  37145. get: function () {
  37146. return this._isEnabled;
  37147. },
  37148. /**
  37149. * Sets wether the image processing is enabled or not.
  37150. */
  37151. set: function (value) {
  37152. if (this._isEnabled === value) {
  37153. return;
  37154. }
  37155. this._isEnabled = value;
  37156. this._updateParameters();
  37157. },
  37158. enumerable: true,
  37159. configurable: true
  37160. });
  37161. /**
  37162. * Method called each time the image processing information changes requires to recompile the effect.
  37163. */
  37164. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37165. this.onUpdateParameters.notifyObservers(this);
  37166. };
  37167. ImageProcessingConfiguration.prototype.getClassName = function () {
  37168. return "ImageProcessingConfiguration";
  37169. };
  37170. /**
  37171. * Prepare the list of uniforms associated with the Image Processing effects.
  37172. * @param uniformsList The list of uniforms used in the effect
  37173. * @param defines the list of defines currently in use
  37174. */
  37175. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37176. if (defines.EXPOSURE) {
  37177. uniforms.push("exposureLinear");
  37178. }
  37179. if (defines.CONTRAST) {
  37180. uniforms.push("contrast");
  37181. }
  37182. if (defines.COLORGRADING) {
  37183. uniforms.push("colorTransformSettings");
  37184. }
  37185. if (defines.VIGNETTE) {
  37186. uniforms.push("vInverseScreenSize");
  37187. uniforms.push("vignetteSettings1");
  37188. uniforms.push("vignetteSettings2");
  37189. }
  37190. if (defines.COLORCURVES) {
  37191. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37192. }
  37193. if (defines.GRAIN) {
  37194. uniforms.push("grainVarianceAmount");
  37195. uniforms.push("grainAnimatedSeed");
  37196. }
  37197. };
  37198. /**
  37199. * Prepare the list of samplers associated with the Image Processing effects.
  37200. * @param uniformsList The list of uniforms used in the effect
  37201. * @param defines the list of defines currently in use
  37202. */
  37203. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37204. if (defines.COLORGRADING) {
  37205. samplersList.push("txColorTransform");
  37206. }
  37207. };
  37208. /**
  37209. * Prepare the list of defines associated to the shader.
  37210. * @param defines the list of defines to complete
  37211. */
  37212. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37213. if (forPostProcess === void 0) { forPostProcess = false; }
  37214. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37215. defines.VIGNETTE = false;
  37216. defines.TONEMAPPING = false;
  37217. defines.CONTRAST = false;
  37218. defines.EXPOSURE = false;
  37219. defines.COLORCURVES = false;
  37220. defines.COLORGRADING = false;
  37221. defines.COLORGRADING3D = false;
  37222. defines.IMAGEPROCESSING = false;
  37223. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37224. return;
  37225. }
  37226. defines.VIGNETTE = this.vignetteEnabled;
  37227. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37228. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37229. defines.TONEMAPPING = this.toneMappingEnabled;
  37230. defines.CONTRAST = (this.contrast !== 1.0);
  37231. defines.EXPOSURE = (this.exposure !== 1.0);
  37232. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37233. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37234. if (defines.COLORGRADING) {
  37235. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37236. }
  37237. else {
  37238. defines.COLORGRADING3D = false;
  37239. }
  37240. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37241. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37242. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37243. defines.GRAIN = this.grainEnabled;
  37244. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37245. };
  37246. /**
  37247. * Returns true if all the image processing information are ready.
  37248. */
  37249. ImageProcessingConfiguration.prototype.isReady = function () {
  37250. // Color Grading texure can not be none blocking.
  37251. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37252. };
  37253. /**
  37254. * Binds the image processing to the shader.
  37255. * @param effect The effect to bind to
  37256. */
  37257. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37258. if (aspectRatio === void 0) { aspectRatio = 1; }
  37259. // Color Curves
  37260. if (this._colorCurvesEnabled && this.colorCurves) {
  37261. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37262. }
  37263. // Vignette
  37264. if (this._vignetteEnabled) {
  37265. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37266. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37267. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37268. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37269. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37270. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37271. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37272. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37273. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37274. var vignettePower = -2.0 * this.vignetteWeight;
  37275. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37276. }
  37277. // Exposure
  37278. effect.setFloat("exposureLinear", this.exposure);
  37279. // Contrast
  37280. effect.setFloat("contrast", this.contrast);
  37281. // Color transform settings
  37282. if (this.colorGradingTexture) {
  37283. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37284. var textureSize = this.colorGradingTexture.getSize().height;
  37285. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37286. 0.5 / textureSize, // textureOffset
  37287. textureSize, // textureSize
  37288. this.colorGradingTexture.level // weight
  37289. );
  37290. }
  37291. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37292. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37293. };
  37294. /**
  37295. * Clones the current image processing instance.
  37296. * @return The cloned image processing
  37297. */
  37298. ImageProcessingConfiguration.prototype.clone = function () {
  37299. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37300. };
  37301. /**
  37302. * Serializes the current image processing instance to a json representation.
  37303. * @return a JSON representation
  37304. */
  37305. ImageProcessingConfiguration.prototype.serialize = function () {
  37306. return BABYLON.SerializationHelper.Serialize(this);
  37307. };
  37308. /**
  37309. * Parses the image processing from a json representation.
  37310. * @param source the JSON source to parse
  37311. * @return The parsed image processing
  37312. */
  37313. ImageProcessingConfiguration.Parse = function (source) {
  37314. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37315. };
  37316. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37317. /**
  37318. * Used to apply the vignette as a mix with the pixel color.
  37319. */
  37320. get: function () {
  37321. return this._VIGNETTEMODE_MULTIPLY;
  37322. },
  37323. enumerable: true,
  37324. configurable: true
  37325. });
  37326. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37327. /**
  37328. * Used to apply the vignette as a replacement of the pixel color.
  37329. */
  37330. get: function () {
  37331. return this._VIGNETTEMODE_OPAQUE;
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. // Static constants associated to the image processing.
  37337. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37338. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37339. __decorate([
  37340. BABYLON.serializeAsColorCurves()
  37341. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37342. __decorate([
  37343. BABYLON.serialize()
  37344. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37345. __decorate([
  37346. BABYLON.serializeAsTexture()
  37347. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37348. __decorate([
  37349. BABYLON.serialize()
  37350. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37351. __decorate([
  37352. BABYLON.serialize()
  37353. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37354. __decorate([
  37355. BABYLON.serialize()
  37356. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37357. __decorate([
  37358. BABYLON.serialize()
  37359. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37360. __decorate([
  37361. BABYLON.serialize()
  37362. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37363. __decorate([
  37364. BABYLON.serialize()
  37365. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37366. __decorate([
  37367. BABYLON.serialize()
  37368. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37369. __decorate([
  37370. BABYLON.serialize()
  37371. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37372. __decorate([
  37373. BABYLON.serialize()
  37374. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37375. __decorate([
  37376. BABYLON.serialize()
  37377. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37378. __decorate([
  37379. BABYLON.serializeAsColor4()
  37380. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37381. __decorate([
  37382. BABYLON.serialize()
  37383. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37384. __decorate([
  37385. BABYLON.serialize()
  37386. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37387. __decorate([
  37388. BABYLON.serialize()
  37389. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37390. __decorate([
  37391. BABYLON.serialize()
  37392. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37393. __decorate([
  37394. BABYLON.serialize()
  37395. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37396. __decorate([
  37397. BABYLON.serialize()
  37398. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37399. __decorate([
  37400. BABYLON.serialize()
  37401. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37402. __decorate([
  37403. BABYLON.serialize()
  37404. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37405. return ImageProcessingConfiguration;
  37406. }());
  37407. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37408. })(BABYLON || (BABYLON = {}));
  37409. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37410. var BABYLON;
  37411. (function (BABYLON) {
  37412. /**
  37413. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37414. * It can help converting any input color in a desired output one. This can then be used to create effects
  37415. * from sepia, black and white to sixties or futuristic rendering...
  37416. *
  37417. * The only supported format is currently 3dl.
  37418. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37419. */
  37420. var ColorGradingTexture = /** @class */ (function (_super) {
  37421. __extends(ColorGradingTexture, _super);
  37422. /**
  37423. * Instantiates a ColorGradingTexture from the following parameters.
  37424. *
  37425. * @param url The location of the color gradind data (currently only supporting 3dl)
  37426. * @param scene The scene the texture will be used in
  37427. */
  37428. function ColorGradingTexture(url, scene) {
  37429. var _this = _super.call(this, scene) || this;
  37430. if (!url) {
  37431. return _this;
  37432. }
  37433. _this._engine = scene.getEngine();
  37434. _this._textureMatrix = BABYLON.Matrix.Identity();
  37435. _this.name = url;
  37436. _this.url = url;
  37437. _this.hasAlpha = false;
  37438. _this.isCube = false;
  37439. _this.is3D = _this._engine.webGLVersion > 1;
  37440. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37441. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37442. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37443. _this.anisotropicFilteringLevel = 1;
  37444. _this._texture = _this._getFromCache(url, true);
  37445. if (!_this._texture) {
  37446. if (!scene.useDelayedTextureLoading) {
  37447. _this.loadTexture();
  37448. }
  37449. else {
  37450. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37451. }
  37452. }
  37453. return _this;
  37454. }
  37455. /**
  37456. * Returns the texture matrix used in most of the material.
  37457. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37458. */
  37459. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37460. return this._textureMatrix;
  37461. };
  37462. /**
  37463. * Occurs when the file being loaded is a .3dl LUT file.
  37464. */
  37465. ColorGradingTexture.prototype.load3dlTexture = function () {
  37466. var engine = this._engine;
  37467. var texture;
  37468. if (engine.webGLVersion === 1) {
  37469. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37470. }
  37471. else {
  37472. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37473. }
  37474. this._texture = texture;
  37475. var callback = function (text) {
  37476. if (typeof text !== "string") {
  37477. return;
  37478. }
  37479. var data = null;
  37480. var tempData = null;
  37481. var line;
  37482. var lines = text.split('\n');
  37483. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37484. var maxColor = 0;
  37485. for (var i = 0; i < lines.length; i++) {
  37486. line = lines[i];
  37487. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37488. continue;
  37489. if (line.indexOf('#') === 0)
  37490. continue;
  37491. var words = line.split(" ");
  37492. if (size === 0) {
  37493. // Number of space + one
  37494. size = words.length;
  37495. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37496. tempData = new Float32Array(size * size * size * 4);
  37497. continue;
  37498. }
  37499. if (size != 0) {
  37500. var r = Math.max(parseInt(words[0]), 0);
  37501. var g = Math.max(parseInt(words[1]), 0);
  37502. var b = Math.max(parseInt(words[2]), 0);
  37503. maxColor = Math.max(r, maxColor);
  37504. maxColor = Math.max(g, maxColor);
  37505. maxColor = Math.max(b, maxColor);
  37506. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37507. if (tempData) {
  37508. tempData[pixelStorageIndex + 0] = r;
  37509. tempData[pixelStorageIndex + 1] = g;
  37510. tempData[pixelStorageIndex + 2] = b;
  37511. }
  37512. pixelIndexSlice++;
  37513. if (pixelIndexSlice % size == 0) {
  37514. pixelIndexH++;
  37515. pixelIndexSlice = 0;
  37516. if (pixelIndexH % size == 0) {
  37517. pixelIndexW++;
  37518. pixelIndexH = 0;
  37519. }
  37520. }
  37521. }
  37522. }
  37523. if (tempData && data) {
  37524. for (var i = 0; i < tempData.length; i++) {
  37525. if (i > 0 && (i + 1) % 4 === 0) {
  37526. data[i] = 255;
  37527. }
  37528. else {
  37529. var value = tempData[i];
  37530. data[i] = (value / maxColor * 255);
  37531. }
  37532. }
  37533. }
  37534. if (texture.is3D) {
  37535. texture.updateSize(size, size, size);
  37536. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37537. }
  37538. else {
  37539. texture.updateSize(size * size, size);
  37540. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37541. }
  37542. };
  37543. var scene = this.getScene();
  37544. if (scene) {
  37545. scene._loadFile(this.url, callback);
  37546. }
  37547. else {
  37548. this._engine._loadFile(this.url, callback);
  37549. }
  37550. return this._texture;
  37551. };
  37552. /**
  37553. * Starts the loading process of the texture.
  37554. */
  37555. ColorGradingTexture.prototype.loadTexture = function () {
  37556. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37557. this.load3dlTexture();
  37558. }
  37559. };
  37560. /**
  37561. * Clones the color gradind texture.
  37562. */
  37563. ColorGradingTexture.prototype.clone = function () {
  37564. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37565. // Base texture
  37566. newTexture.level = this.level;
  37567. return newTexture;
  37568. };
  37569. /**
  37570. * Called during delayed load for textures.
  37571. */
  37572. ColorGradingTexture.prototype.delayLoad = function () {
  37573. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37574. return;
  37575. }
  37576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37577. this._texture = this._getFromCache(this.url, true);
  37578. if (!this._texture) {
  37579. this.loadTexture();
  37580. }
  37581. };
  37582. /**
  37583. * Parses a color grading texture serialized by Babylon.
  37584. * @param parsedTexture The texture information being parsedTexture
  37585. * @param scene The scene to load the texture in
  37586. * @param rootUrl The root url of the data assets to load
  37587. * @return A color gradind texture
  37588. */
  37589. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37590. var texture = null;
  37591. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37592. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37593. texture.name = parsedTexture.name;
  37594. texture.level = parsedTexture.level;
  37595. }
  37596. return texture;
  37597. };
  37598. /**
  37599. * Serializes the LUT texture to json format.
  37600. */
  37601. ColorGradingTexture.prototype.serialize = function () {
  37602. if (!this.name) {
  37603. return null;
  37604. }
  37605. var serializationObject = {};
  37606. serializationObject.name = this.name;
  37607. serializationObject.level = this.level;
  37608. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37609. return serializationObject;
  37610. };
  37611. /**
  37612. * Empty line regex stored for GC.
  37613. */
  37614. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37615. return ColorGradingTexture;
  37616. }(BABYLON.BaseTexture));
  37617. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37618. })(BABYLON || (BABYLON = {}));
  37619. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37620. var BABYLON;
  37621. (function (BABYLON) {
  37622. /**
  37623. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37624. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37625. * 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;
  37626. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37627. */
  37628. var ColorCurves = /** @class */ (function () {
  37629. function ColorCurves() {
  37630. this._dirty = true;
  37631. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37632. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37633. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37634. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37635. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37636. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37637. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37638. this._globalHue = 30;
  37639. this._globalDensity = 0;
  37640. this._globalSaturation = 0;
  37641. this._globalExposure = 0;
  37642. this._highlightsHue = 30;
  37643. this._highlightsDensity = 0;
  37644. this._highlightsSaturation = 0;
  37645. this._highlightsExposure = 0;
  37646. this._midtonesHue = 30;
  37647. this._midtonesDensity = 0;
  37648. this._midtonesSaturation = 0;
  37649. this._midtonesExposure = 0;
  37650. this._shadowsHue = 30;
  37651. this._shadowsDensity = 0;
  37652. this._shadowsSaturation = 0;
  37653. this._shadowsExposure = 0;
  37654. }
  37655. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37656. /**
  37657. * Gets the global Hue value.
  37658. * 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).
  37659. */
  37660. get: function () {
  37661. return this._globalHue;
  37662. },
  37663. /**
  37664. * Sets the global Hue value.
  37665. * 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).
  37666. */
  37667. set: function (value) {
  37668. this._globalHue = value;
  37669. this._dirty = true;
  37670. },
  37671. enumerable: true,
  37672. configurable: true
  37673. });
  37674. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37675. /**
  37676. * Gets the global Density value.
  37677. * 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.
  37678. * Values less than zero provide a filter of opposite hue.
  37679. */
  37680. get: function () {
  37681. return this._globalDensity;
  37682. },
  37683. /**
  37684. * Sets the global Density value.
  37685. * 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.
  37686. * Values less than zero provide a filter of opposite hue.
  37687. */
  37688. set: function (value) {
  37689. this._globalDensity = value;
  37690. this._dirty = true;
  37691. },
  37692. enumerable: true,
  37693. configurable: true
  37694. });
  37695. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37696. /**
  37697. * Gets the global Saturation value.
  37698. * 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.
  37699. */
  37700. get: function () {
  37701. return this._globalSaturation;
  37702. },
  37703. /**
  37704. * Sets the global Saturation value.
  37705. * 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.
  37706. */
  37707. set: function (value) {
  37708. this._globalSaturation = value;
  37709. this._dirty = true;
  37710. },
  37711. enumerable: true,
  37712. configurable: true
  37713. });
  37714. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37715. /**
  37716. * Gets the highlights Hue value.
  37717. * 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).
  37718. */
  37719. get: function () {
  37720. return this._highlightsHue;
  37721. },
  37722. /**
  37723. * Sets the highlights Hue value.
  37724. * 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).
  37725. */
  37726. set: function (value) {
  37727. this._highlightsHue = value;
  37728. this._dirty = true;
  37729. },
  37730. enumerable: true,
  37731. configurable: true
  37732. });
  37733. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37734. /**
  37735. * Gets the highlights Density value.
  37736. * 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.
  37737. * Values less than zero provide a filter of opposite hue.
  37738. */
  37739. get: function () {
  37740. return this._highlightsDensity;
  37741. },
  37742. /**
  37743. * Sets the highlights Density value.
  37744. * 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.
  37745. * Values less than zero provide a filter of opposite hue.
  37746. */
  37747. set: function (value) {
  37748. this._highlightsDensity = value;
  37749. this._dirty = true;
  37750. },
  37751. enumerable: true,
  37752. configurable: true
  37753. });
  37754. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37755. /**
  37756. * Gets the highlights Saturation value.
  37757. * 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.
  37758. */
  37759. get: function () {
  37760. return this._highlightsSaturation;
  37761. },
  37762. /**
  37763. * Sets the highlights Saturation value.
  37764. * 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.
  37765. */
  37766. set: function (value) {
  37767. this._highlightsSaturation = value;
  37768. this._dirty = true;
  37769. },
  37770. enumerable: true,
  37771. configurable: true
  37772. });
  37773. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37774. /**
  37775. * Gets the highlights Exposure value.
  37776. * 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.
  37777. */
  37778. get: function () {
  37779. return this._highlightsExposure;
  37780. },
  37781. /**
  37782. * Sets the highlights Exposure value.
  37783. * 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.
  37784. */
  37785. set: function (value) {
  37786. this._highlightsExposure = value;
  37787. this._dirty = true;
  37788. },
  37789. enumerable: true,
  37790. configurable: true
  37791. });
  37792. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37793. /**
  37794. * Gets the midtones Hue value.
  37795. * 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).
  37796. */
  37797. get: function () {
  37798. return this._midtonesHue;
  37799. },
  37800. /**
  37801. * Sets the midtones Hue value.
  37802. * 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).
  37803. */
  37804. set: function (value) {
  37805. this._midtonesHue = value;
  37806. this._dirty = true;
  37807. },
  37808. enumerable: true,
  37809. configurable: true
  37810. });
  37811. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37812. /**
  37813. * Gets the midtones Density value.
  37814. * 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.
  37815. * Values less than zero provide a filter of opposite hue.
  37816. */
  37817. get: function () {
  37818. return this._midtonesDensity;
  37819. },
  37820. /**
  37821. * Sets the midtones Density value.
  37822. * 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.
  37823. * Values less than zero provide a filter of opposite hue.
  37824. */
  37825. set: function (value) {
  37826. this._midtonesDensity = value;
  37827. this._dirty = true;
  37828. },
  37829. enumerable: true,
  37830. configurable: true
  37831. });
  37832. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37833. /**
  37834. * Gets the midtones Saturation value.
  37835. * 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.
  37836. */
  37837. get: function () {
  37838. return this._midtonesSaturation;
  37839. },
  37840. /**
  37841. * Sets the midtones Saturation value.
  37842. * 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.
  37843. */
  37844. set: function (value) {
  37845. this._midtonesSaturation = value;
  37846. this._dirty = true;
  37847. },
  37848. enumerable: true,
  37849. configurable: true
  37850. });
  37851. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37852. /**
  37853. * Gets the midtones Exposure value.
  37854. * 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.
  37855. */
  37856. get: function () {
  37857. return this._midtonesExposure;
  37858. },
  37859. /**
  37860. * Sets the midtones Exposure value.
  37861. * 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.
  37862. */
  37863. set: function (value) {
  37864. this._midtonesExposure = value;
  37865. this._dirty = true;
  37866. },
  37867. enumerable: true,
  37868. configurable: true
  37869. });
  37870. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37871. /**
  37872. * Gets the shadows Hue value.
  37873. * 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).
  37874. */
  37875. get: function () {
  37876. return this._shadowsHue;
  37877. },
  37878. /**
  37879. * Sets the shadows Hue value.
  37880. * 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).
  37881. */
  37882. set: function (value) {
  37883. this._shadowsHue = value;
  37884. this._dirty = true;
  37885. },
  37886. enumerable: true,
  37887. configurable: true
  37888. });
  37889. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37890. /**
  37891. * Gets the shadows Density value.
  37892. * 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.
  37893. * Values less than zero provide a filter of opposite hue.
  37894. */
  37895. get: function () {
  37896. return this._shadowsDensity;
  37897. },
  37898. /**
  37899. * Sets the shadows Density value.
  37900. * 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.
  37901. * Values less than zero provide a filter of opposite hue.
  37902. */
  37903. set: function (value) {
  37904. this._shadowsDensity = value;
  37905. this._dirty = true;
  37906. },
  37907. enumerable: true,
  37908. configurable: true
  37909. });
  37910. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37911. /**
  37912. * Gets the shadows Saturation value.
  37913. * 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.
  37914. */
  37915. get: function () {
  37916. return this._shadowsSaturation;
  37917. },
  37918. /**
  37919. * Sets the shadows Saturation value.
  37920. * 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.
  37921. */
  37922. set: function (value) {
  37923. this._shadowsSaturation = value;
  37924. this._dirty = true;
  37925. },
  37926. enumerable: true,
  37927. configurable: true
  37928. });
  37929. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37930. /**
  37931. * Gets the shadows Exposure value.
  37932. * 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.
  37933. */
  37934. get: function () {
  37935. return this._shadowsExposure;
  37936. },
  37937. /**
  37938. * Sets the shadows Exposure value.
  37939. * 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.
  37940. */
  37941. set: function (value) {
  37942. this._shadowsExposure = value;
  37943. this._dirty = true;
  37944. },
  37945. enumerable: true,
  37946. configurable: true
  37947. });
  37948. ColorCurves.prototype.getClassName = function () {
  37949. return "ColorCurves";
  37950. };
  37951. /**
  37952. * Binds the color curves to the shader.
  37953. * @param colorCurves The color curve to bind
  37954. * @param effect The effect to bind to
  37955. */
  37956. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37957. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37958. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37959. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37960. if (colorCurves._dirty) {
  37961. colorCurves._dirty = false;
  37962. // Fill in global info.
  37963. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37964. // Compute highlights info.
  37965. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37966. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37967. // Compute midtones info.
  37968. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37969. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37970. // Compute shadows info.
  37971. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37972. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37973. // Compute deltas (neutral is midtones).
  37974. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37975. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37976. }
  37977. if (effect) {
  37978. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37979. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37980. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37981. }
  37982. };
  37983. /**
  37984. * Prepare the list of uniforms associated with the ColorCurves effects.
  37985. * @param uniformsList The list of uniforms used in the effect
  37986. */
  37987. ColorCurves.PrepareUniforms = function (uniformsList) {
  37988. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37989. };
  37990. /**
  37991. * Returns color grading data based on a hue, density, saturation and exposure value.
  37992. * @param filterHue The hue of the color filter.
  37993. * @param filterDensity The density of the color filter.
  37994. * @param saturation The saturation.
  37995. * @param exposure The exposure.
  37996. * @param result The result data container.
  37997. */
  37998. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37999. if (hue == null) {
  38000. return;
  38001. }
  38002. hue = ColorCurves.clamp(hue, 0, 360);
  38003. density = ColorCurves.clamp(density, -100, 100);
  38004. saturation = ColorCurves.clamp(saturation, -100, 100);
  38005. exposure = ColorCurves.clamp(exposure, -100, 100);
  38006. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38007. // so that the maximum filter density is only 50% control. This provides fine control
  38008. // for small values and reasonable range.
  38009. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38010. density *= 0.5;
  38011. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38012. if (density < 0) {
  38013. density *= -1;
  38014. hue = (hue + 180) % 360;
  38015. }
  38016. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38017. result.scaleToRef(2, result);
  38018. result.a = 1 + 0.01 * saturation;
  38019. };
  38020. /**
  38021. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38022. * @param value The input slider value in range [-100,100].
  38023. * @returns Adjusted value.
  38024. */
  38025. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38026. value /= 100;
  38027. var x = Math.abs(value);
  38028. x = Math.pow(x, 2);
  38029. if (value < 0) {
  38030. x *= -1;
  38031. }
  38032. x *= 100;
  38033. return x;
  38034. };
  38035. /**
  38036. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38037. * @param hue The hue (H) input.
  38038. * @param saturation The saturation (S) input.
  38039. * @param brightness The brightness (B) input.
  38040. * @result An RGBA color represented as Vector4.
  38041. */
  38042. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38043. var h = ColorCurves.clamp(hue, 0, 360);
  38044. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38045. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38046. if (s === 0) {
  38047. result.r = v;
  38048. result.g = v;
  38049. result.b = v;
  38050. }
  38051. else {
  38052. // sector 0 to 5
  38053. h /= 60;
  38054. var i = Math.floor(h);
  38055. // fractional part of h
  38056. var f = h - i;
  38057. var p = v * (1 - s);
  38058. var q = v * (1 - s * f);
  38059. var t = v * (1 - s * (1 - f));
  38060. switch (i) {
  38061. case 0:
  38062. result.r = v;
  38063. result.g = t;
  38064. result.b = p;
  38065. break;
  38066. case 1:
  38067. result.r = q;
  38068. result.g = v;
  38069. result.b = p;
  38070. break;
  38071. case 2:
  38072. result.r = p;
  38073. result.g = v;
  38074. result.b = t;
  38075. break;
  38076. case 3:
  38077. result.r = p;
  38078. result.g = q;
  38079. result.b = v;
  38080. break;
  38081. case 4:
  38082. result.r = t;
  38083. result.g = p;
  38084. result.b = v;
  38085. break;
  38086. default:// case 5:
  38087. result.r = v;
  38088. result.g = p;
  38089. result.b = q;
  38090. break;
  38091. }
  38092. }
  38093. result.a = 1;
  38094. };
  38095. /**
  38096. * Returns a value clamped between min and max
  38097. * @param value The value to clamp
  38098. * @param min The minimum of value
  38099. * @param max The maximum of value
  38100. * @returns The clamped value.
  38101. */
  38102. ColorCurves.clamp = function (value, min, max) {
  38103. return Math.min(Math.max(value, min), max);
  38104. };
  38105. /**
  38106. * Clones the current color curve instance.
  38107. * @return The cloned curves
  38108. */
  38109. ColorCurves.prototype.clone = function () {
  38110. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38111. };
  38112. /**
  38113. * Serializes the current color curve instance to a json representation.
  38114. * @return a JSON representation
  38115. */
  38116. ColorCurves.prototype.serialize = function () {
  38117. return BABYLON.SerializationHelper.Serialize(this);
  38118. };
  38119. /**
  38120. * Parses the color curve from a json representation.
  38121. * @param source the JSON source to parse
  38122. * @return The parsed curves
  38123. */
  38124. ColorCurves.Parse = function (source) {
  38125. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38126. };
  38127. __decorate([
  38128. BABYLON.serialize()
  38129. ], ColorCurves.prototype, "_globalHue", void 0);
  38130. __decorate([
  38131. BABYLON.serialize()
  38132. ], ColorCurves.prototype, "_globalDensity", void 0);
  38133. __decorate([
  38134. BABYLON.serialize()
  38135. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38136. __decorate([
  38137. BABYLON.serialize()
  38138. ], ColorCurves.prototype, "_globalExposure", void 0);
  38139. __decorate([
  38140. BABYLON.serialize()
  38141. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38142. __decorate([
  38143. BABYLON.serialize()
  38144. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38145. __decorate([
  38146. BABYLON.serialize()
  38147. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38148. __decorate([
  38149. BABYLON.serialize()
  38150. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38151. __decorate([
  38152. BABYLON.serialize()
  38153. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38154. __decorate([
  38155. BABYLON.serialize()
  38156. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38157. __decorate([
  38158. BABYLON.serialize()
  38159. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38160. __decorate([
  38161. BABYLON.serialize()
  38162. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38163. return ColorCurves;
  38164. }());
  38165. BABYLON.ColorCurves = ColorCurves;
  38166. })(BABYLON || (BABYLON = {}));
  38167. //# sourceMappingURL=babylon.colorCurves.js.map
  38168. //# sourceMappingURL=babylon.behavior.js.map
  38169. var BABYLON;
  38170. (function (BABYLON) {
  38171. /**
  38172. * "Static Class" containing the most commonly used helper while dealing with material for
  38173. * rendering purpose.
  38174. *
  38175. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38176. *
  38177. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38178. */
  38179. var MaterialHelper = /** @class */ (function () {
  38180. function MaterialHelper() {
  38181. }
  38182. /**
  38183. * Bind the current view position to an effect.
  38184. * @param effect The effect to be bound
  38185. * @param scene The scene the eyes position is used from
  38186. */
  38187. MaterialHelper.BindEyePosition = function (effect, scene) {
  38188. if (scene._forcedViewPosition) {
  38189. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38190. return;
  38191. }
  38192. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38193. };
  38194. /**
  38195. * Helps preparing the defines values about the UVs in used in the effect.
  38196. * UVs are shared as much as we can accross chanels in the shaders.
  38197. * @param texture The texture we are preparing the UVs for
  38198. * @param defines The defines to update
  38199. * @param key The chanel key "diffuse", "specular"... used in the shader
  38200. */
  38201. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38202. defines._needUVs = true;
  38203. defines[key] = true;
  38204. if (texture.getTextureMatrix().isIdentity(true)) {
  38205. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38206. if (texture.coordinatesIndex === 0) {
  38207. defines["MAINUV1"] = true;
  38208. }
  38209. else {
  38210. defines["MAINUV2"] = true;
  38211. }
  38212. }
  38213. else {
  38214. defines[key + "DIRECTUV"] = 0;
  38215. }
  38216. };
  38217. /**
  38218. * Binds a texture matrix value to its corrsponding uniform
  38219. * @param texture The texture to bind the matrix for
  38220. * @param uniformBuffer The uniform buffer receivin the data
  38221. * @param key The chanel key "diffuse", "specular"... used in the shader
  38222. */
  38223. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38224. var matrix = texture.getTextureMatrix();
  38225. if (!matrix.isIdentity(true)) {
  38226. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38227. }
  38228. };
  38229. /**
  38230. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38231. * @param mesh defines the current mesh
  38232. * @param scene defines the current scene
  38233. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38234. * @param pointsCloud defines if point cloud rendering has to be turned on
  38235. * @param fogEnabled defines if fog has to be turned on
  38236. * @param alphaTest defines if alpha testing has to be turned on
  38237. * @param defines defines the current list of defines
  38238. */
  38239. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38240. if (defines._areMiscDirty) {
  38241. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38242. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38243. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38244. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38245. defines["ALPHATEST"] = alphaTest;
  38246. }
  38247. };
  38248. /**
  38249. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38250. * @param scene defines the current scene
  38251. * @param engine defines the current engine
  38252. * @param defines specifies the list of active defines
  38253. * @param useInstances defines if instances have to be turned on
  38254. * @param useClipPlane defines if clip plane have to be turned on
  38255. */
  38256. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38257. if (useClipPlane === void 0) { useClipPlane = null; }
  38258. var changed = false;
  38259. if (useClipPlane == null) {
  38260. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38261. }
  38262. if (defines["CLIPPLANE"] !== useClipPlane) {
  38263. defines["CLIPPLANE"] = useClipPlane;
  38264. changed = true;
  38265. }
  38266. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38267. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38268. changed = true;
  38269. }
  38270. if (defines["INSTANCES"] !== useInstances) {
  38271. defines["INSTANCES"] = useInstances;
  38272. changed = true;
  38273. }
  38274. if (changed) {
  38275. defines.markAsUnprocessed();
  38276. }
  38277. };
  38278. /**
  38279. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38280. * @param mesh The mesh containing the geometry data we will draw
  38281. * @param defines The defines to update
  38282. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38283. * @param useBones Precise whether bones should be used or not (override mesh info)
  38284. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38285. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38286. * @returns false if defines are considered not dirty and have not been checked
  38287. */
  38288. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38289. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38290. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38291. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38292. return false;
  38293. }
  38294. defines._normals = defines._needNormals;
  38295. defines._uvs = defines._needUVs;
  38296. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38297. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38298. defines["TANGENT"] = true;
  38299. }
  38300. if (defines._needUVs) {
  38301. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38302. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38303. }
  38304. else {
  38305. defines["UV1"] = false;
  38306. defines["UV2"] = false;
  38307. }
  38308. if (useVertexColor) {
  38309. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38310. defines["VERTEXCOLOR"] = hasVertexColors;
  38311. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38312. }
  38313. if (useBones) {
  38314. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38315. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38316. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38317. }
  38318. else {
  38319. defines["NUM_BONE_INFLUENCERS"] = 0;
  38320. defines["BonesPerMesh"] = 0;
  38321. }
  38322. }
  38323. if (useMorphTargets) {
  38324. var manager = mesh.morphTargetManager;
  38325. if (manager) {
  38326. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38327. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38328. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38329. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38330. }
  38331. else {
  38332. defines["MORPHTARGETS_TANGENT"] = false;
  38333. defines["MORPHTARGETS_NORMAL"] = false;
  38334. defines["MORPHTARGETS"] = false;
  38335. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38336. }
  38337. }
  38338. return true;
  38339. };
  38340. /**
  38341. * Prepares the defines related to the light information passed in parameter
  38342. * @param scene The scene we are intending to draw
  38343. * @param mesh The mesh the effect is compiling for
  38344. * @param defines The defines to update
  38345. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38346. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38347. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38348. * @returns true if normals will be required for the rest of the effect
  38349. */
  38350. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38351. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38352. if (disableLighting === void 0) { disableLighting = false; }
  38353. if (!defines._areLightsDirty) {
  38354. return defines._needNormals;
  38355. }
  38356. var lightIndex = 0;
  38357. var needNormals = false;
  38358. var needRebuild = false;
  38359. var lightmapMode = false;
  38360. var shadowEnabled = false;
  38361. var specularEnabled = false;
  38362. if (scene.lightsEnabled && !disableLighting) {
  38363. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38364. var light = _a[_i];
  38365. needNormals = true;
  38366. if (defines["LIGHT" + lightIndex] === undefined) {
  38367. needRebuild = true;
  38368. }
  38369. defines["LIGHT" + lightIndex] = true;
  38370. defines["SPOTLIGHT" + lightIndex] = false;
  38371. defines["HEMILIGHT" + lightIndex] = false;
  38372. defines["POINTLIGHT" + lightIndex] = false;
  38373. defines["DIRLIGHT" + lightIndex] = false;
  38374. var type;
  38375. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38376. type = "SPOTLIGHT" + lightIndex;
  38377. var spotLight = light;
  38378. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38379. }
  38380. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38381. type = "HEMILIGHT" + lightIndex;
  38382. }
  38383. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38384. type = "POINTLIGHT" + lightIndex;
  38385. }
  38386. else {
  38387. type = "DIRLIGHT" + lightIndex;
  38388. }
  38389. defines[type] = true;
  38390. // Specular
  38391. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38392. specularEnabled = true;
  38393. }
  38394. // Shadows
  38395. defines["SHADOW" + lightIndex] = false;
  38396. defines["SHADOWPCF" + lightIndex] = false;
  38397. defines["SHADOWESM" + lightIndex] = false;
  38398. defines["SHADOWCUBE" + lightIndex] = false;
  38399. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38400. var shadowGenerator = light.getShadowGenerator();
  38401. if (shadowGenerator) {
  38402. shadowEnabled = true;
  38403. shadowGenerator.prepareDefines(defines, lightIndex);
  38404. }
  38405. }
  38406. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38407. lightmapMode = true;
  38408. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38409. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38410. }
  38411. else {
  38412. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38413. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38414. }
  38415. lightIndex++;
  38416. if (lightIndex === maxSimultaneousLights)
  38417. break;
  38418. }
  38419. }
  38420. defines["SPECULARTERM"] = specularEnabled;
  38421. defines["SHADOWS"] = shadowEnabled;
  38422. // Resetting all other lights if any
  38423. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38424. if (defines["LIGHT" + index] !== undefined) {
  38425. defines["LIGHT" + index] = false;
  38426. defines["HEMILIGHT" + lightIndex] = false;
  38427. defines["POINTLIGHT" + lightIndex] = false;
  38428. defines["DIRLIGHT" + lightIndex] = false;
  38429. defines["SPOTLIGHT" + lightIndex] = false;
  38430. defines["SHADOW" + lightIndex] = false;
  38431. }
  38432. }
  38433. var caps = scene.getEngine().getCaps();
  38434. if (defines["SHADOWFLOAT"] === undefined) {
  38435. needRebuild = true;
  38436. }
  38437. defines["SHADOWFLOAT"] = shadowEnabled &&
  38438. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38439. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38440. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38441. if (needRebuild) {
  38442. defines.rebuild();
  38443. }
  38444. return needNormals;
  38445. };
  38446. /**
  38447. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38448. * that won t be acctive due to defines being turned off.
  38449. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38450. * @param samplersList The samplers list
  38451. * @param defines The defines helping in the list generation
  38452. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38453. */
  38454. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38455. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38456. var uniformsList;
  38457. var uniformBuffersList = null;
  38458. if (uniformsListOrOptions.uniformsNames) {
  38459. var options = uniformsListOrOptions;
  38460. uniformsList = options.uniformsNames;
  38461. uniformBuffersList = options.uniformBuffersNames;
  38462. samplersList = options.samplers;
  38463. defines = options.defines;
  38464. maxSimultaneousLights = options.maxSimultaneousLights;
  38465. }
  38466. else {
  38467. uniformsList = uniformsListOrOptions;
  38468. if (!samplersList) {
  38469. samplersList = [];
  38470. }
  38471. }
  38472. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38473. if (!defines["LIGHT" + lightIndex]) {
  38474. break;
  38475. }
  38476. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38477. if (uniformBuffersList) {
  38478. uniformBuffersList.push("Light" + lightIndex);
  38479. }
  38480. samplersList.push("shadowSampler" + lightIndex);
  38481. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38482. samplersList.push("projectionLightSampler" + lightIndex);
  38483. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38484. }
  38485. }
  38486. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38487. uniformsList.push("morphTargetInfluences");
  38488. }
  38489. };
  38490. /**
  38491. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38492. * @param defines The defines to update while falling back
  38493. * @param fallbacks The authorized effect fallbacks
  38494. * @param maxSimultaneousLights The maximum number of lights allowed
  38495. * @param rank the current rank of the Effect
  38496. * @returns The newly affected rank
  38497. */
  38498. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38499. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38500. if (rank === void 0) { rank = 0; }
  38501. var lightFallbackRank = 0;
  38502. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38503. if (!defines["LIGHT" + lightIndex]) {
  38504. break;
  38505. }
  38506. if (lightIndex > 0) {
  38507. lightFallbackRank = rank + lightIndex;
  38508. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38509. }
  38510. if (!defines["SHADOWS"]) {
  38511. if (defines["SHADOW" + lightIndex]) {
  38512. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38513. }
  38514. if (defines["SHADOWPCF" + lightIndex]) {
  38515. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38516. }
  38517. if (defines["SHADOWESM" + lightIndex]) {
  38518. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38519. }
  38520. }
  38521. }
  38522. return lightFallbackRank++;
  38523. };
  38524. /**
  38525. * Prepares the list of attributes required for morph targets according to the effect defines.
  38526. * @param attribs The current list of supported attribs
  38527. * @param mesh The mesh to prepare the morph targets attributes for
  38528. * @param defines The current Defines of the effect
  38529. */
  38530. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38531. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38532. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38533. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38534. var manager = mesh.morphTargetManager;
  38535. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38536. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38537. for (var index = 0; index < influencers; index++) {
  38538. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38539. if (normal) {
  38540. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38541. }
  38542. if (tangent) {
  38543. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38544. }
  38545. if (attribs.length > maxAttributesCount) {
  38546. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38547. }
  38548. }
  38549. }
  38550. };
  38551. /**
  38552. * Prepares the list of attributes required for bones according to the effect defines.
  38553. * @param attribs The current list of supported attribs
  38554. * @param mesh The mesh to prepare the bones attributes for
  38555. * @param defines The current Defines of the effect
  38556. * @param fallbacks The current efffect fallback strategy
  38557. */
  38558. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38559. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38560. fallbacks.addCPUSkinningFallback(0, mesh);
  38561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38563. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38566. }
  38567. }
  38568. };
  38569. /**
  38570. * Prepares the list of attributes required for instances according to the effect defines.
  38571. * @param attribs The current list of supported attribs
  38572. * @param defines The current Defines of the effect
  38573. */
  38574. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38575. if (defines["INSTANCES"]) {
  38576. attribs.push("world0");
  38577. attribs.push("world1");
  38578. attribs.push("world2");
  38579. attribs.push("world3");
  38580. }
  38581. };
  38582. /**
  38583. * Binds the light shadow information to the effect for the given mesh.
  38584. * @param light The light containing the generator
  38585. * @param scene The scene the lights belongs to
  38586. * @param mesh The mesh we are binding the information to render
  38587. * @param lightIndex The light index in the effect used to render the mesh
  38588. * @param effect The effect we are binding the data to
  38589. */
  38590. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38591. if (light.shadowEnabled && mesh.receiveShadows) {
  38592. var shadowGenerator = light.getShadowGenerator();
  38593. if (shadowGenerator) {
  38594. shadowGenerator.bindShadowLight(lightIndex, effect);
  38595. }
  38596. }
  38597. };
  38598. /**
  38599. * Binds the light information to the effect.
  38600. * @param light The light containing the generator
  38601. * @param effect The effect we are binding the data to
  38602. * @param lightIndex The light index in the effect used to render
  38603. */
  38604. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38605. light.transferToEffect(effect, lightIndex + "");
  38606. };
  38607. /**
  38608. * Binds the lights information from the scene to the effect for the given mesh.
  38609. * @param scene The scene the lights belongs to
  38610. * @param mesh The mesh we are binding the information to render
  38611. * @param effect The effect we are binding the data to
  38612. * @param defines The generated defines for the effect
  38613. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38614. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38615. */
  38616. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38617. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38618. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38619. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38620. for (var i = 0; i < len; i++) {
  38621. var light = mesh._lightSources[i];
  38622. var iAsString = i.toString();
  38623. var scaledIntensity = light.getScaledIntensity();
  38624. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38625. MaterialHelper.BindLightProperties(light, effect, i);
  38626. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38627. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38628. if (defines["SPECULARTERM"]) {
  38629. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38630. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38631. }
  38632. // Shadows
  38633. if (scene.shadowsEnabled) {
  38634. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38635. }
  38636. light._uniformBuffer.update();
  38637. }
  38638. };
  38639. /**
  38640. * Binds the fog information from the scene to the effect for the given mesh.
  38641. * @param scene The scene the lights belongs to
  38642. * @param mesh The mesh we are binding the information to render
  38643. * @param effect The effect we are binding the data to
  38644. */
  38645. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38646. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38647. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38648. effect.setColor3("vFogColor", scene.fogColor);
  38649. }
  38650. };
  38651. /**
  38652. * Binds the bones information from the mesh to the effect.
  38653. * @param mesh The mesh we are binding the information to render
  38654. * @param effect The effect we are binding the data to
  38655. */
  38656. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38657. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38658. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38659. if (matrices && effect) {
  38660. effect.setMatrices("mBones", matrices);
  38661. }
  38662. }
  38663. };
  38664. /**
  38665. * Binds the morph targets information from the mesh to the effect.
  38666. * @param abstractMesh The mesh we are binding the information to render
  38667. * @param effect The effect we are binding the data to
  38668. */
  38669. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38670. var manager = abstractMesh.morphTargetManager;
  38671. if (!abstractMesh || !manager) {
  38672. return;
  38673. }
  38674. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38675. };
  38676. /**
  38677. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38678. * @param defines The generated defines used in the effect
  38679. * @param effect The effect we are binding the data to
  38680. * @param scene The scene we are willing to render with logarithmic scale for
  38681. */
  38682. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38683. if (defines["LOGARITHMICDEPTH"]) {
  38684. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38685. }
  38686. };
  38687. /**
  38688. * Binds the clip plane information from the scene to the effect.
  38689. * @param scene The scene the clip plane information are extracted from
  38690. * @param effect The effect we are binding the data to
  38691. */
  38692. MaterialHelper.BindClipPlane = function (effect, scene) {
  38693. if (scene.clipPlane) {
  38694. var clipPlane = scene.clipPlane;
  38695. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38696. }
  38697. };
  38698. return MaterialHelper;
  38699. }());
  38700. BABYLON.MaterialHelper = MaterialHelper;
  38701. })(BABYLON || (BABYLON = {}));
  38702. //# sourceMappingURL=babylon.materialHelper.js.map
  38703. var BABYLON;
  38704. (function (BABYLON) {
  38705. var PushMaterial = /** @class */ (function (_super) {
  38706. __extends(PushMaterial, _super);
  38707. function PushMaterial(name, scene) {
  38708. var _this = _super.call(this, name, scene) || this;
  38709. _this._normalMatrix = new BABYLON.Matrix();
  38710. _this.storeEffectOnSubMeshes = true;
  38711. return _this;
  38712. }
  38713. PushMaterial.prototype.getEffect = function () {
  38714. return this._activeEffect;
  38715. };
  38716. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38717. if (!mesh) {
  38718. return false;
  38719. }
  38720. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38721. return true;
  38722. }
  38723. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38724. };
  38725. /**
  38726. * Binds the given world matrix to the active effect
  38727. *
  38728. * @param world the matrix to bind
  38729. */
  38730. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38731. this._activeEffect.setMatrix("world", world);
  38732. };
  38733. /**
  38734. * Binds the given normal matrix to the active effect
  38735. *
  38736. * @param normalMatrix the matrix to bind
  38737. */
  38738. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38739. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38740. };
  38741. PushMaterial.prototype.bind = function (world, mesh) {
  38742. if (!mesh) {
  38743. return;
  38744. }
  38745. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38746. };
  38747. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38748. if (effect === void 0) { effect = null; }
  38749. _super.prototype._afterBind.call(this, mesh);
  38750. this.getScene()._cachedEffect = effect;
  38751. };
  38752. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38753. if (visibility === void 0) { visibility = 1; }
  38754. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38755. };
  38756. return PushMaterial;
  38757. }(BABYLON.Material));
  38758. BABYLON.PushMaterial = PushMaterial;
  38759. })(BABYLON || (BABYLON = {}));
  38760. //# sourceMappingURL=babylon.pushMaterial.js.map
  38761. var BABYLON;
  38762. (function (BABYLON) {
  38763. /** @ignore */
  38764. var StandardMaterialDefines = /** @class */ (function (_super) {
  38765. __extends(StandardMaterialDefines, _super);
  38766. function StandardMaterialDefines() {
  38767. var _this = _super.call(this) || this;
  38768. _this.MAINUV1 = false;
  38769. _this.MAINUV2 = false;
  38770. _this.DIFFUSE = false;
  38771. _this.DIFFUSEDIRECTUV = 0;
  38772. _this.AMBIENT = false;
  38773. _this.AMBIENTDIRECTUV = 0;
  38774. _this.OPACITY = false;
  38775. _this.OPACITYDIRECTUV = 0;
  38776. _this.OPACITYRGB = false;
  38777. _this.REFLECTION = false;
  38778. _this.EMISSIVE = false;
  38779. _this.EMISSIVEDIRECTUV = 0;
  38780. _this.SPECULAR = false;
  38781. _this.SPECULARDIRECTUV = 0;
  38782. _this.BUMP = false;
  38783. _this.BUMPDIRECTUV = 0;
  38784. _this.PARALLAX = false;
  38785. _this.PARALLAXOCCLUSION = false;
  38786. _this.SPECULAROVERALPHA = false;
  38787. _this.CLIPPLANE = false;
  38788. _this.ALPHATEST = false;
  38789. _this.DEPTHPREPASS = false;
  38790. _this.ALPHAFROMDIFFUSE = false;
  38791. _this.POINTSIZE = false;
  38792. _this.FOG = false;
  38793. _this.SPECULARTERM = false;
  38794. _this.DIFFUSEFRESNEL = false;
  38795. _this.OPACITYFRESNEL = false;
  38796. _this.REFLECTIONFRESNEL = false;
  38797. _this.REFRACTIONFRESNEL = false;
  38798. _this.EMISSIVEFRESNEL = false;
  38799. _this.FRESNEL = false;
  38800. _this.NORMAL = false;
  38801. _this.UV1 = false;
  38802. _this.UV2 = false;
  38803. _this.VERTEXCOLOR = false;
  38804. _this.VERTEXALPHA = false;
  38805. _this.NUM_BONE_INFLUENCERS = 0;
  38806. _this.BonesPerMesh = 0;
  38807. _this.INSTANCES = false;
  38808. _this.GLOSSINESS = false;
  38809. _this.ROUGHNESS = false;
  38810. _this.EMISSIVEASILLUMINATION = false;
  38811. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38812. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38813. _this.LIGHTMAP = false;
  38814. _this.LIGHTMAPDIRECTUV = 0;
  38815. _this.OBJECTSPACE_NORMALMAP = false;
  38816. _this.USELIGHTMAPASSHADOWMAP = false;
  38817. _this.REFLECTIONMAP_3D = false;
  38818. _this.REFLECTIONMAP_SPHERICAL = false;
  38819. _this.REFLECTIONMAP_PLANAR = false;
  38820. _this.REFLECTIONMAP_CUBIC = false;
  38821. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38822. _this.REFLECTIONMAP_PROJECTION = false;
  38823. _this.REFLECTIONMAP_SKYBOX = false;
  38824. _this.REFLECTIONMAP_EXPLICIT = false;
  38825. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38826. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38827. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38828. _this.INVERTCUBICMAP = false;
  38829. _this.LOGARITHMICDEPTH = false;
  38830. _this.REFRACTION = false;
  38831. _this.REFRACTIONMAP_3D = false;
  38832. _this.REFLECTIONOVERALPHA = false;
  38833. _this.TWOSIDEDLIGHTING = false;
  38834. _this.SHADOWFLOAT = false;
  38835. _this.MORPHTARGETS = false;
  38836. _this.MORPHTARGETS_NORMAL = false;
  38837. _this.MORPHTARGETS_TANGENT = false;
  38838. _this.NUM_MORPH_INFLUENCERS = 0;
  38839. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38840. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38841. _this.IMAGEPROCESSING = false;
  38842. _this.VIGNETTE = false;
  38843. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38844. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38845. _this.TONEMAPPING = false;
  38846. _this.CONTRAST = false;
  38847. _this.COLORCURVES = false;
  38848. _this.COLORGRADING = false;
  38849. _this.COLORGRADING3D = false;
  38850. _this.SAMPLER3DGREENDEPTH = false;
  38851. _this.SAMPLER3DBGRMAP = false;
  38852. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38853. _this.EXPOSURE = false;
  38854. _this.GRAIN = false;
  38855. _this.rebuild();
  38856. return _this;
  38857. }
  38858. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38859. var modes = [
  38860. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38861. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38862. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38863. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38864. ];
  38865. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38866. var mode = modes_1[_i];
  38867. this[mode] = (mode === modeToEnable);
  38868. }
  38869. };
  38870. return StandardMaterialDefines;
  38871. }(BABYLON.MaterialDefines));
  38872. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38873. var StandardMaterial = /** @class */ (function (_super) {
  38874. __extends(StandardMaterial, _super);
  38875. function StandardMaterial(name, scene) {
  38876. var _this = _super.call(this, name, scene) || this;
  38877. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38878. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38879. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38880. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38881. _this.specularPower = 64;
  38882. _this._useAlphaFromDiffuseTexture = false;
  38883. _this._useEmissiveAsIllumination = false;
  38884. _this._linkEmissiveWithDiffuse = false;
  38885. _this._useSpecularOverAlpha = false;
  38886. _this._useReflectionOverAlpha = false;
  38887. _this._disableLighting = false;
  38888. _this._useObjectSpaceNormalMap = false;
  38889. _this._useParallax = false;
  38890. _this._useParallaxOcclusion = false;
  38891. _this.parallaxScaleBias = 0.05;
  38892. _this._roughness = 0;
  38893. _this.indexOfRefraction = 0.98;
  38894. _this.invertRefractionY = true;
  38895. _this._useLightmapAsShadowmap = false;
  38896. _this._useReflectionFresnelFromSpecular = false;
  38897. _this._useGlossinessFromSpecularMapAlpha = false;
  38898. _this._maxSimultaneousLights = 4;
  38899. /**
  38900. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38901. */
  38902. _this._invertNormalMapX = false;
  38903. /**
  38904. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38905. */
  38906. _this._invertNormalMapY = false;
  38907. /**
  38908. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38909. */
  38910. _this._twoSidedLighting = false;
  38911. _this._renderTargets = new BABYLON.SmartArray(16);
  38912. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38913. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38914. // Setup the default processing configuration to the scene.
  38915. _this._attachImageProcessingConfiguration(null);
  38916. _this.getRenderTargetTextures = function () {
  38917. _this._renderTargets.reset();
  38918. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38919. _this._renderTargets.push(_this._reflectionTexture);
  38920. }
  38921. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38922. _this._renderTargets.push(_this._refractionTexture);
  38923. }
  38924. return _this._renderTargets;
  38925. };
  38926. return _this;
  38927. }
  38928. ;
  38929. ;
  38930. ;
  38931. ;
  38932. ;
  38933. ;
  38934. ;
  38935. ;
  38936. ;
  38937. ;
  38938. ;
  38939. ;
  38940. ;
  38941. ;
  38942. ;
  38943. ;
  38944. ;
  38945. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38946. /**
  38947. * Gets the image processing configuration used either in this material.
  38948. */
  38949. get: function () {
  38950. return this._imageProcessingConfiguration;
  38951. },
  38952. /**
  38953. * Sets the Default image processing configuration used either in the this material.
  38954. *
  38955. * If sets to null, the scene one is in use.
  38956. */
  38957. set: function (value) {
  38958. this._attachImageProcessingConfiguration(value);
  38959. // Ensure the effect will be rebuilt.
  38960. this._markAllSubMeshesAsTexturesDirty();
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. /**
  38966. * Attaches a new image processing configuration to the Standard Material.
  38967. * @param configuration
  38968. */
  38969. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38970. var _this = this;
  38971. if (configuration === this._imageProcessingConfiguration) {
  38972. return;
  38973. }
  38974. // Detaches observer.
  38975. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38976. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38977. }
  38978. // Pick the scene configuration if needed.
  38979. if (!configuration) {
  38980. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38981. }
  38982. else {
  38983. this._imageProcessingConfiguration = configuration;
  38984. }
  38985. // Attaches observer.
  38986. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38987. _this._markAllSubMeshesAsImageProcessingDirty();
  38988. });
  38989. };
  38990. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38991. /**
  38992. * Gets wether the color curves effect is enabled.
  38993. */
  38994. get: function () {
  38995. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38996. },
  38997. /**
  38998. * Sets wether the color curves effect is enabled.
  38999. */
  39000. set: function (value) {
  39001. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39002. },
  39003. enumerable: true,
  39004. configurable: true
  39005. });
  39006. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39007. /**
  39008. * Gets wether the color grading effect is enabled.
  39009. */
  39010. get: function () {
  39011. return this.imageProcessingConfiguration.colorGradingEnabled;
  39012. },
  39013. /**
  39014. * Gets wether the color grading effect is enabled.
  39015. */
  39016. set: function (value) {
  39017. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39018. },
  39019. enumerable: true,
  39020. configurable: true
  39021. });
  39022. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39023. /**
  39024. * Gets wether tonemapping is enabled or not.
  39025. */
  39026. get: function () {
  39027. return this._imageProcessingConfiguration.toneMappingEnabled;
  39028. },
  39029. /**
  39030. * Sets wether tonemapping is enabled or not
  39031. */
  39032. set: function (value) {
  39033. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39034. },
  39035. enumerable: true,
  39036. configurable: true
  39037. });
  39038. ;
  39039. ;
  39040. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39041. /**
  39042. * The camera exposure used on this material.
  39043. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39044. * This corresponds to a photographic exposure.
  39045. */
  39046. get: function () {
  39047. return this._imageProcessingConfiguration.exposure;
  39048. },
  39049. /**
  39050. * The camera exposure used on this material.
  39051. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39052. * This corresponds to a photographic exposure.
  39053. */
  39054. set: function (value) {
  39055. this._imageProcessingConfiguration.exposure = value;
  39056. },
  39057. enumerable: true,
  39058. configurable: true
  39059. });
  39060. ;
  39061. ;
  39062. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39063. /**
  39064. * Gets The camera contrast used on this material.
  39065. */
  39066. get: function () {
  39067. return this._imageProcessingConfiguration.contrast;
  39068. },
  39069. /**
  39070. * Sets The camera contrast used on this material.
  39071. */
  39072. set: function (value) {
  39073. this._imageProcessingConfiguration.contrast = value;
  39074. },
  39075. enumerable: true,
  39076. configurable: true
  39077. });
  39078. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39079. /**
  39080. * Gets the Color Grading 2D Lookup Texture.
  39081. */
  39082. get: function () {
  39083. return this._imageProcessingConfiguration.colorGradingTexture;
  39084. },
  39085. /**
  39086. * Sets the Color Grading 2D Lookup Texture.
  39087. */
  39088. set: function (value) {
  39089. this._imageProcessingConfiguration.colorGradingTexture = value;
  39090. },
  39091. enumerable: true,
  39092. configurable: true
  39093. });
  39094. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39095. /**
  39096. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39097. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39098. * 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;
  39099. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39100. */
  39101. get: function () {
  39102. return this._imageProcessingConfiguration.colorCurves;
  39103. },
  39104. /**
  39105. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39106. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39107. * 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;
  39108. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39109. */
  39110. set: function (value) {
  39111. this._imageProcessingConfiguration.colorCurves = value;
  39112. },
  39113. enumerable: true,
  39114. configurable: true
  39115. });
  39116. StandardMaterial.prototype.getClassName = function () {
  39117. return "StandardMaterial";
  39118. };
  39119. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39120. get: function () {
  39121. return this._useLogarithmicDepth;
  39122. },
  39123. set: function (value) {
  39124. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39125. this._markAllSubMeshesAsMiscDirty();
  39126. },
  39127. enumerable: true,
  39128. configurable: true
  39129. });
  39130. StandardMaterial.prototype.needAlphaBlending = function () {
  39131. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39132. };
  39133. StandardMaterial.prototype.needAlphaTesting = function () {
  39134. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39135. };
  39136. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39137. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39138. };
  39139. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39140. return this._diffuseTexture;
  39141. };
  39142. /**
  39143. * Child classes can use it to update shaders
  39144. */
  39145. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39146. if (useInstances === void 0) { useInstances = false; }
  39147. if (subMesh.effect && this.isFrozen) {
  39148. if (this._wasPreviouslyReady && subMesh.effect) {
  39149. return true;
  39150. }
  39151. }
  39152. if (!subMesh._materialDefines) {
  39153. subMesh._materialDefines = new StandardMaterialDefines();
  39154. }
  39155. var scene = this.getScene();
  39156. var defines = subMesh._materialDefines;
  39157. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39158. if (defines._renderId === scene.getRenderId()) {
  39159. return true;
  39160. }
  39161. }
  39162. var engine = scene.getEngine();
  39163. // Lights
  39164. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39165. // Textures
  39166. if (defines._areTexturesDirty) {
  39167. defines._needUVs = false;
  39168. defines.MAINUV1 = false;
  39169. defines.MAINUV2 = false;
  39170. if (scene.texturesEnabled) {
  39171. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39172. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39173. return false;
  39174. }
  39175. else {
  39176. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39177. }
  39178. }
  39179. else {
  39180. defines.DIFFUSE = false;
  39181. }
  39182. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39183. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39184. return false;
  39185. }
  39186. else {
  39187. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39188. }
  39189. }
  39190. else {
  39191. defines.AMBIENT = false;
  39192. }
  39193. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39194. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39195. return false;
  39196. }
  39197. else {
  39198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39199. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39200. }
  39201. }
  39202. else {
  39203. defines.OPACITY = false;
  39204. }
  39205. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39206. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39207. return false;
  39208. }
  39209. else {
  39210. defines._needNormals = true;
  39211. defines.REFLECTION = true;
  39212. defines.ROUGHNESS = (this._roughness > 0);
  39213. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39214. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39215. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39216. switch (this._reflectionTexture.coordinatesMode) {
  39217. case BABYLON.Texture.CUBIC_MODE:
  39218. case BABYLON.Texture.INVCUBIC_MODE:
  39219. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39220. break;
  39221. case BABYLON.Texture.EXPLICIT_MODE:
  39222. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39223. break;
  39224. case BABYLON.Texture.PLANAR_MODE:
  39225. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39226. break;
  39227. case BABYLON.Texture.PROJECTION_MODE:
  39228. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39229. break;
  39230. case BABYLON.Texture.SKYBOX_MODE:
  39231. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39232. break;
  39233. case BABYLON.Texture.SPHERICAL_MODE:
  39234. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39235. break;
  39236. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39237. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39238. break;
  39239. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39240. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39241. break;
  39242. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39243. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39244. break;
  39245. }
  39246. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39247. }
  39248. }
  39249. else {
  39250. defines.REFLECTION = false;
  39251. }
  39252. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39253. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39254. return false;
  39255. }
  39256. else {
  39257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39258. }
  39259. }
  39260. else {
  39261. defines.EMISSIVE = false;
  39262. }
  39263. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39264. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39265. return false;
  39266. }
  39267. else {
  39268. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39269. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39270. }
  39271. }
  39272. else {
  39273. defines.LIGHTMAP = false;
  39274. }
  39275. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39276. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39277. return false;
  39278. }
  39279. else {
  39280. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39281. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39282. }
  39283. }
  39284. else {
  39285. defines.SPECULAR = false;
  39286. }
  39287. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39288. // Bump texure can not be not blocking.
  39289. if (!this._bumpTexture.isReady()) {
  39290. return false;
  39291. }
  39292. else {
  39293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39294. defines.PARALLAX = this._useParallax;
  39295. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39296. }
  39297. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39298. }
  39299. else {
  39300. defines.BUMP = false;
  39301. }
  39302. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39303. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39304. return false;
  39305. }
  39306. else {
  39307. defines._needUVs = true;
  39308. defines.REFRACTION = true;
  39309. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39310. }
  39311. }
  39312. else {
  39313. defines.REFRACTION = false;
  39314. }
  39315. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39316. }
  39317. else {
  39318. defines.DIFFUSE = false;
  39319. defines.AMBIENT = false;
  39320. defines.OPACITY = false;
  39321. defines.REFLECTION = false;
  39322. defines.EMISSIVE = false;
  39323. defines.LIGHTMAP = false;
  39324. defines.BUMP = false;
  39325. defines.REFRACTION = false;
  39326. }
  39327. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39328. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39329. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39330. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39331. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39332. }
  39333. if (defines._areImageProcessingDirty) {
  39334. if (!this._imageProcessingConfiguration.isReady()) {
  39335. return false;
  39336. }
  39337. this._imageProcessingConfiguration.prepareDefines(defines);
  39338. }
  39339. if (defines._areFresnelDirty) {
  39340. if (StandardMaterial.FresnelEnabled) {
  39341. // Fresnel
  39342. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39343. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39344. this._reflectionFresnelParameters) {
  39345. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39346. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39347. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39348. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39349. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39350. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39351. defines._needNormals = true;
  39352. defines.FRESNEL = true;
  39353. }
  39354. }
  39355. else {
  39356. defines.FRESNEL = false;
  39357. }
  39358. }
  39359. // Misc.
  39360. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39361. // Attribs
  39362. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39363. // Values that need to be evaluated on every frame
  39364. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39365. // Get correct effect
  39366. if (defines.isDirty) {
  39367. defines.markAsProcessed();
  39368. scene.resetCachedMaterial();
  39369. // Fallbacks
  39370. var fallbacks = new BABYLON.EffectFallbacks();
  39371. if (defines.REFLECTION) {
  39372. fallbacks.addFallback(0, "REFLECTION");
  39373. }
  39374. if (defines.SPECULAR) {
  39375. fallbacks.addFallback(0, "SPECULAR");
  39376. }
  39377. if (defines.BUMP) {
  39378. fallbacks.addFallback(0, "BUMP");
  39379. }
  39380. if (defines.PARALLAX) {
  39381. fallbacks.addFallback(1, "PARALLAX");
  39382. }
  39383. if (defines.PARALLAXOCCLUSION) {
  39384. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39385. }
  39386. if (defines.SPECULAROVERALPHA) {
  39387. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39388. }
  39389. if (defines.FOG) {
  39390. fallbacks.addFallback(1, "FOG");
  39391. }
  39392. if (defines.POINTSIZE) {
  39393. fallbacks.addFallback(0, "POINTSIZE");
  39394. }
  39395. if (defines.LOGARITHMICDEPTH) {
  39396. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39397. }
  39398. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39399. if (defines.SPECULARTERM) {
  39400. fallbacks.addFallback(0, "SPECULARTERM");
  39401. }
  39402. if (defines.DIFFUSEFRESNEL) {
  39403. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39404. }
  39405. if (defines.OPACITYFRESNEL) {
  39406. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39407. }
  39408. if (defines.REFLECTIONFRESNEL) {
  39409. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39410. }
  39411. if (defines.EMISSIVEFRESNEL) {
  39412. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39413. }
  39414. if (defines.FRESNEL) {
  39415. fallbacks.addFallback(4, "FRESNEL");
  39416. }
  39417. //Attributes
  39418. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39419. if (defines.NORMAL) {
  39420. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39421. }
  39422. if (defines.UV1) {
  39423. attribs.push(BABYLON.VertexBuffer.UVKind);
  39424. }
  39425. if (defines.UV2) {
  39426. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39427. }
  39428. if (defines.VERTEXCOLOR) {
  39429. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39430. }
  39431. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39432. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39433. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39434. var shaderName = "default";
  39435. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39436. "vFogInfos", "vFogColor", "pointSize",
  39437. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39438. "mBones",
  39439. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39440. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39441. "vReflectionPosition", "vReflectionSize",
  39442. "logarithmicDepthConstant", "vTangentSpaceParams"
  39443. ];
  39444. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39445. var uniformBuffers = ["Material", "Scene"];
  39446. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39447. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39448. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39449. uniformsNames: uniforms,
  39450. uniformBuffersNames: uniformBuffers,
  39451. samplers: samplers,
  39452. defines: defines,
  39453. maxSimultaneousLights: this._maxSimultaneousLights
  39454. });
  39455. if (this.customShaderNameResolve) {
  39456. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39457. }
  39458. var join = defines.toString();
  39459. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39460. attributes: attribs,
  39461. uniformsNames: uniforms,
  39462. uniformBuffersNames: uniformBuffers,
  39463. samplers: samplers,
  39464. defines: join,
  39465. fallbacks: fallbacks,
  39466. onCompiled: this.onCompiled,
  39467. onError: this.onError,
  39468. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39469. }, engine), defines);
  39470. this.buildUniformLayout();
  39471. }
  39472. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39473. return false;
  39474. }
  39475. defines._renderId = scene.getRenderId();
  39476. this._wasPreviouslyReady = true;
  39477. return true;
  39478. };
  39479. StandardMaterial.prototype.buildUniformLayout = function () {
  39480. // Order is important !
  39481. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39482. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39483. this._uniformBuffer.addUniform("opacityParts", 4);
  39484. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39485. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39486. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39487. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39488. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39489. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39490. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39491. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39492. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39493. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39494. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39495. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39496. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39497. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39498. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39499. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39500. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39501. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39502. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39503. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39504. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39505. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39506. this._uniformBuffer.addUniform("specularMatrix", 16);
  39507. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39508. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39509. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39510. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39511. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39512. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39513. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39514. this._uniformBuffer.addUniform("pointSize", 1);
  39515. this._uniformBuffer.create();
  39516. };
  39517. StandardMaterial.prototype.unbind = function () {
  39518. if (this._activeEffect) {
  39519. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39520. this._activeEffect.setTexture("reflection2DSampler", null);
  39521. }
  39522. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39523. this._activeEffect.setTexture("refraction2DSampler", null);
  39524. }
  39525. }
  39526. _super.prototype.unbind.call(this);
  39527. };
  39528. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39529. var scene = this.getScene();
  39530. var defines = subMesh._materialDefines;
  39531. if (!defines) {
  39532. return;
  39533. }
  39534. var effect = subMesh.effect;
  39535. if (!effect) {
  39536. return;
  39537. }
  39538. this._activeEffect = effect;
  39539. // Matrices
  39540. this.bindOnlyWorldMatrix(world);
  39541. // Normal Matrix
  39542. if (defines.OBJECTSPACE_NORMALMAP) {
  39543. world.toNormalMatrix(this._normalMatrix);
  39544. this.bindOnlyNormalMatrix(this._normalMatrix);
  39545. }
  39546. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39547. // Bones
  39548. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39549. if (mustRebind) {
  39550. this._uniformBuffer.bindToEffect(effect, "Material");
  39551. this.bindViewProjection(effect);
  39552. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39553. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39554. // Fresnel
  39555. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39556. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39557. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39558. }
  39559. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39560. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39561. }
  39562. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39563. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39564. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39565. }
  39566. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39567. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39568. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39569. }
  39570. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39571. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39572. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39573. }
  39574. }
  39575. // Textures
  39576. if (scene.texturesEnabled) {
  39577. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39578. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39579. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39580. }
  39581. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39582. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39583. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39584. }
  39585. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39586. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39587. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39588. }
  39589. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39590. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39591. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39592. if (this._reflectionTexture.boundingBoxSize) {
  39593. var cubeTexture = this._reflectionTexture;
  39594. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39595. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39596. }
  39597. }
  39598. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39599. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39600. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39601. }
  39602. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39603. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39604. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39605. }
  39606. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39607. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39608. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39609. }
  39610. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39611. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39612. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39613. if (scene._mirroredCameraPosition) {
  39614. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39615. }
  39616. else {
  39617. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39618. }
  39619. }
  39620. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39621. var depth = 1.0;
  39622. if (!this._refractionTexture.isCube) {
  39623. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39624. if (this._refractionTexture.depth) {
  39625. depth = this._refractionTexture.depth;
  39626. }
  39627. }
  39628. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39629. }
  39630. }
  39631. // Point size
  39632. if (this.pointsCloud) {
  39633. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39634. }
  39635. if (defines.SPECULARTERM) {
  39636. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39637. }
  39638. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39639. // Diffuse
  39640. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39641. }
  39642. // Textures
  39643. if (scene.texturesEnabled) {
  39644. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39645. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39646. }
  39647. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39648. effect.setTexture("ambientSampler", this._ambientTexture);
  39649. }
  39650. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39651. effect.setTexture("opacitySampler", this._opacityTexture);
  39652. }
  39653. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39654. if (this._reflectionTexture.isCube) {
  39655. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39656. }
  39657. else {
  39658. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39659. }
  39660. }
  39661. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39662. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39663. }
  39664. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39665. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39666. }
  39667. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39668. effect.setTexture("specularSampler", this._specularTexture);
  39669. }
  39670. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39671. effect.setTexture("bumpSampler", this._bumpTexture);
  39672. }
  39673. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39674. var depth = 1.0;
  39675. if (this._refractionTexture.isCube) {
  39676. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39677. }
  39678. else {
  39679. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39680. }
  39681. }
  39682. }
  39683. // Clip plane
  39684. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39685. // Colors
  39686. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39687. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39688. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39689. }
  39690. if (mustRebind || !this.isFrozen) {
  39691. // Lights
  39692. if (scene.lightsEnabled && !this._disableLighting) {
  39693. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39694. }
  39695. // View
  39696. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39697. this.bindView(effect);
  39698. }
  39699. // Fog
  39700. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39701. // Morph targets
  39702. if (defines.NUM_MORPH_INFLUENCERS) {
  39703. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39704. }
  39705. // Log. depth
  39706. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39707. // image processing
  39708. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39709. this._imageProcessingConfiguration.bind(this._activeEffect);
  39710. }
  39711. }
  39712. this._uniformBuffer.update();
  39713. this._afterBind(mesh, this._activeEffect);
  39714. };
  39715. StandardMaterial.prototype.getAnimatables = function () {
  39716. var results = [];
  39717. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39718. results.push(this._diffuseTexture);
  39719. }
  39720. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39721. results.push(this._ambientTexture);
  39722. }
  39723. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39724. results.push(this._opacityTexture);
  39725. }
  39726. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39727. results.push(this._reflectionTexture);
  39728. }
  39729. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39730. results.push(this._emissiveTexture);
  39731. }
  39732. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39733. results.push(this._specularTexture);
  39734. }
  39735. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39736. results.push(this._bumpTexture);
  39737. }
  39738. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39739. results.push(this._lightmapTexture);
  39740. }
  39741. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39742. results.push(this._refractionTexture);
  39743. }
  39744. return results;
  39745. };
  39746. StandardMaterial.prototype.getActiveTextures = function () {
  39747. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39748. if (this._diffuseTexture) {
  39749. activeTextures.push(this._diffuseTexture);
  39750. }
  39751. if (this._ambientTexture) {
  39752. activeTextures.push(this._ambientTexture);
  39753. }
  39754. if (this._opacityTexture) {
  39755. activeTextures.push(this._opacityTexture);
  39756. }
  39757. if (this._reflectionTexture) {
  39758. activeTextures.push(this._reflectionTexture);
  39759. }
  39760. if (this._emissiveTexture) {
  39761. activeTextures.push(this._emissiveTexture);
  39762. }
  39763. if (this._specularTexture) {
  39764. activeTextures.push(this._specularTexture);
  39765. }
  39766. if (this._bumpTexture) {
  39767. activeTextures.push(this._bumpTexture);
  39768. }
  39769. if (this._lightmapTexture) {
  39770. activeTextures.push(this._lightmapTexture);
  39771. }
  39772. if (this._refractionTexture) {
  39773. activeTextures.push(this._refractionTexture);
  39774. }
  39775. return activeTextures;
  39776. };
  39777. StandardMaterial.prototype.hasTexture = function (texture) {
  39778. if (_super.prototype.hasTexture.call(this, texture)) {
  39779. return true;
  39780. }
  39781. if (this._diffuseTexture === texture) {
  39782. return true;
  39783. }
  39784. if (this._ambientTexture === texture) {
  39785. return true;
  39786. }
  39787. if (this._opacityTexture === texture) {
  39788. return true;
  39789. }
  39790. if (this._reflectionTexture === texture) {
  39791. return true;
  39792. }
  39793. if (this._emissiveTexture === texture) {
  39794. return true;
  39795. }
  39796. if (this._specularTexture === texture) {
  39797. return true;
  39798. }
  39799. if (this._bumpTexture === texture) {
  39800. return true;
  39801. }
  39802. if (this._lightmapTexture === texture) {
  39803. return true;
  39804. }
  39805. if (this._refractionTexture === texture) {
  39806. return true;
  39807. }
  39808. return false;
  39809. };
  39810. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39811. if (forceDisposeTextures) {
  39812. if (this._diffuseTexture) {
  39813. this._diffuseTexture.dispose();
  39814. }
  39815. if (this._ambientTexture) {
  39816. this._ambientTexture.dispose();
  39817. }
  39818. if (this._opacityTexture) {
  39819. this._opacityTexture.dispose();
  39820. }
  39821. if (this._reflectionTexture) {
  39822. this._reflectionTexture.dispose();
  39823. }
  39824. if (this._emissiveTexture) {
  39825. this._emissiveTexture.dispose();
  39826. }
  39827. if (this._specularTexture) {
  39828. this._specularTexture.dispose();
  39829. }
  39830. if (this._bumpTexture) {
  39831. this._bumpTexture.dispose();
  39832. }
  39833. if (this._lightmapTexture) {
  39834. this._lightmapTexture.dispose();
  39835. }
  39836. if (this._refractionTexture) {
  39837. this._refractionTexture.dispose();
  39838. }
  39839. }
  39840. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39841. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39842. }
  39843. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39844. };
  39845. StandardMaterial.prototype.clone = function (name) {
  39846. var _this = this;
  39847. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39848. result.name = name;
  39849. result.id = name;
  39850. return result;
  39851. };
  39852. StandardMaterial.prototype.serialize = function () {
  39853. return BABYLON.SerializationHelper.Serialize(this);
  39854. };
  39855. // Statics
  39856. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39857. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39858. };
  39859. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39860. get: function () {
  39861. return StandardMaterial._DiffuseTextureEnabled;
  39862. },
  39863. set: function (value) {
  39864. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39865. return;
  39866. }
  39867. StandardMaterial._DiffuseTextureEnabled = value;
  39868. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39874. get: function () {
  39875. return StandardMaterial._AmbientTextureEnabled;
  39876. },
  39877. set: function (value) {
  39878. if (StandardMaterial._AmbientTextureEnabled === value) {
  39879. return;
  39880. }
  39881. StandardMaterial._AmbientTextureEnabled = value;
  39882. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39888. get: function () {
  39889. return StandardMaterial._OpacityTextureEnabled;
  39890. },
  39891. set: function (value) {
  39892. if (StandardMaterial._OpacityTextureEnabled === value) {
  39893. return;
  39894. }
  39895. StandardMaterial._OpacityTextureEnabled = value;
  39896. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39897. },
  39898. enumerable: true,
  39899. configurable: true
  39900. });
  39901. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39902. get: function () {
  39903. return StandardMaterial._ReflectionTextureEnabled;
  39904. },
  39905. set: function (value) {
  39906. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39907. return;
  39908. }
  39909. StandardMaterial._ReflectionTextureEnabled = value;
  39910. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39911. },
  39912. enumerable: true,
  39913. configurable: true
  39914. });
  39915. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39916. get: function () {
  39917. return StandardMaterial._EmissiveTextureEnabled;
  39918. },
  39919. set: function (value) {
  39920. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39921. return;
  39922. }
  39923. StandardMaterial._EmissiveTextureEnabled = value;
  39924. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39925. },
  39926. enumerable: true,
  39927. configurable: true
  39928. });
  39929. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39930. get: function () {
  39931. return StandardMaterial._SpecularTextureEnabled;
  39932. },
  39933. set: function (value) {
  39934. if (StandardMaterial._SpecularTextureEnabled === value) {
  39935. return;
  39936. }
  39937. StandardMaterial._SpecularTextureEnabled = value;
  39938. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39939. },
  39940. enumerable: true,
  39941. configurable: true
  39942. });
  39943. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39944. get: function () {
  39945. return StandardMaterial._BumpTextureEnabled;
  39946. },
  39947. set: function (value) {
  39948. if (StandardMaterial._BumpTextureEnabled === value) {
  39949. return;
  39950. }
  39951. StandardMaterial._BumpTextureEnabled = value;
  39952. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39953. },
  39954. enumerable: true,
  39955. configurable: true
  39956. });
  39957. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39958. get: function () {
  39959. return StandardMaterial._LightmapTextureEnabled;
  39960. },
  39961. set: function (value) {
  39962. if (StandardMaterial._LightmapTextureEnabled === value) {
  39963. return;
  39964. }
  39965. StandardMaterial._LightmapTextureEnabled = value;
  39966. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39967. },
  39968. enumerable: true,
  39969. configurable: true
  39970. });
  39971. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39972. get: function () {
  39973. return StandardMaterial._RefractionTextureEnabled;
  39974. },
  39975. set: function (value) {
  39976. if (StandardMaterial._RefractionTextureEnabled === value) {
  39977. return;
  39978. }
  39979. StandardMaterial._RefractionTextureEnabled = value;
  39980. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39986. get: function () {
  39987. return StandardMaterial._ColorGradingTextureEnabled;
  39988. },
  39989. set: function (value) {
  39990. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39991. return;
  39992. }
  39993. StandardMaterial._ColorGradingTextureEnabled = value;
  39994. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39995. },
  39996. enumerable: true,
  39997. configurable: true
  39998. });
  39999. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40000. get: function () {
  40001. return StandardMaterial._FresnelEnabled;
  40002. },
  40003. set: function (value) {
  40004. if (StandardMaterial._FresnelEnabled === value) {
  40005. return;
  40006. }
  40007. StandardMaterial._FresnelEnabled = value;
  40008. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40009. },
  40010. enumerable: true,
  40011. configurable: true
  40012. });
  40013. // Flags used to enable or disable a type of texture for all Standard Materials
  40014. StandardMaterial._DiffuseTextureEnabled = true;
  40015. StandardMaterial._AmbientTextureEnabled = true;
  40016. StandardMaterial._OpacityTextureEnabled = true;
  40017. StandardMaterial._ReflectionTextureEnabled = true;
  40018. StandardMaterial._EmissiveTextureEnabled = true;
  40019. StandardMaterial._SpecularTextureEnabled = true;
  40020. StandardMaterial._BumpTextureEnabled = true;
  40021. StandardMaterial._LightmapTextureEnabled = true;
  40022. StandardMaterial._RefractionTextureEnabled = true;
  40023. StandardMaterial._ColorGradingTextureEnabled = true;
  40024. StandardMaterial._FresnelEnabled = true;
  40025. __decorate([
  40026. BABYLON.serializeAsTexture("diffuseTexture")
  40027. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40028. __decorate([
  40029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40030. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40031. __decorate([
  40032. BABYLON.serializeAsTexture("ambientTexture")
  40033. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40034. __decorate([
  40035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40036. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40037. __decorate([
  40038. BABYLON.serializeAsTexture("opacityTexture")
  40039. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40040. __decorate([
  40041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40042. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40043. __decorate([
  40044. BABYLON.serializeAsTexture("reflectionTexture")
  40045. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40046. __decorate([
  40047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40048. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40049. __decorate([
  40050. BABYLON.serializeAsTexture("emissiveTexture")
  40051. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40052. __decorate([
  40053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40054. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40055. __decorate([
  40056. BABYLON.serializeAsTexture("specularTexture")
  40057. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40058. __decorate([
  40059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40060. ], StandardMaterial.prototype, "specularTexture", void 0);
  40061. __decorate([
  40062. BABYLON.serializeAsTexture("bumpTexture")
  40063. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40064. __decorate([
  40065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40066. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40067. __decorate([
  40068. BABYLON.serializeAsTexture("lightmapTexture")
  40069. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40070. __decorate([
  40071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40072. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40073. __decorate([
  40074. BABYLON.serializeAsTexture("refractionTexture")
  40075. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40076. __decorate([
  40077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40078. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40079. __decorate([
  40080. BABYLON.serializeAsColor3("ambient")
  40081. ], StandardMaterial.prototype, "ambientColor", void 0);
  40082. __decorate([
  40083. BABYLON.serializeAsColor3("diffuse")
  40084. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40085. __decorate([
  40086. BABYLON.serializeAsColor3("specular")
  40087. ], StandardMaterial.prototype, "specularColor", void 0);
  40088. __decorate([
  40089. BABYLON.serializeAsColor3("emissive")
  40090. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40091. __decorate([
  40092. BABYLON.serialize()
  40093. ], StandardMaterial.prototype, "specularPower", void 0);
  40094. __decorate([
  40095. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40096. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40097. __decorate([
  40098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40099. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40100. __decorate([
  40101. BABYLON.serialize("useEmissiveAsIllumination")
  40102. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40103. __decorate([
  40104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40105. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40106. __decorate([
  40107. BABYLON.serialize("linkEmissiveWithDiffuse")
  40108. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40109. __decorate([
  40110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40111. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40112. __decorate([
  40113. BABYLON.serialize("useSpecularOverAlpha")
  40114. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40115. __decorate([
  40116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40117. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40118. __decorate([
  40119. BABYLON.serialize("useReflectionOverAlpha")
  40120. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40121. __decorate([
  40122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40123. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40124. __decorate([
  40125. BABYLON.serialize("disableLighting")
  40126. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40127. __decorate([
  40128. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40129. ], StandardMaterial.prototype, "disableLighting", void 0);
  40130. __decorate([
  40131. BABYLON.serialize("useObjectSpaceNormalMap")
  40132. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40133. __decorate([
  40134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40135. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40136. __decorate([
  40137. BABYLON.serialize("useParallax")
  40138. ], StandardMaterial.prototype, "_useParallax", void 0);
  40139. __decorate([
  40140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40141. ], StandardMaterial.prototype, "useParallax", void 0);
  40142. __decorate([
  40143. BABYLON.serialize("useParallaxOcclusion")
  40144. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40145. __decorate([
  40146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40147. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40148. __decorate([
  40149. BABYLON.serialize()
  40150. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40151. __decorate([
  40152. BABYLON.serialize("roughness")
  40153. ], StandardMaterial.prototype, "_roughness", void 0);
  40154. __decorate([
  40155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40156. ], StandardMaterial.prototype, "roughness", void 0);
  40157. __decorate([
  40158. BABYLON.serialize()
  40159. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40160. __decorate([
  40161. BABYLON.serialize()
  40162. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40163. __decorate([
  40164. BABYLON.serialize("useLightmapAsShadowmap")
  40165. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40166. __decorate([
  40167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40168. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40169. __decorate([
  40170. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40171. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40172. __decorate([
  40173. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40174. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40175. __decorate([
  40176. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40177. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40178. __decorate([
  40179. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40180. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40181. __decorate([
  40182. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40183. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40184. __decorate([
  40185. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40186. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40187. __decorate([
  40188. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40189. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40190. __decorate([
  40191. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40192. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40193. __decorate([
  40194. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40195. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40196. __decorate([
  40197. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40198. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40199. __decorate([
  40200. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40201. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40202. __decorate([
  40203. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40204. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40205. __decorate([
  40206. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40207. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40208. __decorate([
  40209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40210. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40211. __decorate([
  40212. BABYLON.serialize("maxSimultaneousLights")
  40213. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40214. __decorate([
  40215. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40216. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40217. __decorate([
  40218. BABYLON.serialize("invertNormalMapX")
  40219. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40220. __decorate([
  40221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40222. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40223. __decorate([
  40224. BABYLON.serialize("invertNormalMapY")
  40225. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40226. __decorate([
  40227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40228. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40229. __decorate([
  40230. BABYLON.serialize("twoSidedLighting")
  40231. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40232. __decorate([
  40233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40234. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40235. __decorate([
  40236. BABYLON.serialize()
  40237. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40238. return StandardMaterial;
  40239. }(BABYLON.PushMaterial));
  40240. BABYLON.StandardMaterial = StandardMaterial;
  40241. })(BABYLON || (BABYLON = {}));
  40242. //# sourceMappingURL=babylon.standardMaterial.js.map
  40243. var BABYLON;
  40244. (function (BABYLON) {
  40245. /**
  40246. * Manages the defines for the PBR Material.
  40247. */
  40248. var PBRMaterialDefines = /** @class */ (function (_super) {
  40249. __extends(PBRMaterialDefines, _super);
  40250. /**
  40251. * Initializes the PBR Material defines.
  40252. */
  40253. function PBRMaterialDefines() {
  40254. var _this = _super.call(this) || this;
  40255. _this.PBR = true;
  40256. _this.MAINUV1 = false;
  40257. _this.MAINUV2 = false;
  40258. _this.UV1 = false;
  40259. _this.UV2 = false;
  40260. _this.ALBEDO = false;
  40261. _this.ALBEDODIRECTUV = 0;
  40262. _this.VERTEXCOLOR = false;
  40263. _this.AMBIENT = false;
  40264. _this.AMBIENTDIRECTUV = 0;
  40265. _this.AMBIENTINGRAYSCALE = false;
  40266. _this.OPACITY = false;
  40267. _this.VERTEXALPHA = false;
  40268. _this.OPACITYDIRECTUV = 0;
  40269. _this.OPACITYRGB = false;
  40270. _this.ALPHATEST = false;
  40271. _this.DEPTHPREPASS = false;
  40272. _this.ALPHABLEND = false;
  40273. _this.ALPHAFROMALBEDO = false;
  40274. _this.ALPHATESTVALUE = 0.5;
  40275. _this.SPECULAROVERALPHA = false;
  40276. _this.RADIANCEOVERALPHA = false;
  40277. _this.ALPHAFRESNEL = false;
  40278. _this.LINEARALPHAFRESNEL = false;
  40279. _this.PREMULTIPLYALPHA = false;
  40280. _this.EMISSIVE = false;
  40281. _this.EMISSIVEDIRECTUV = 0;
  40282. _this.REFLECTIVITY = false;
  40283. _this.REFLECTIVITYDIRECTUV = 0;
  40284. _this.SPECULARTERM = false;
  40285. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40286. _this.MICROSURFACEAUTOMATIC = false;
  40287. _this.LODBASEDMICROSFURACE = false;
  40288. _this.MICROSURFACEMAP = false;
  40289. _this.MICROSURFACEMAPDIRECTUV = 0;
  40290. _this.METALLICWORKFLOW = false;
  40291. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40292. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40293. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40294. _this.AOSTOREINMETALMAPRED = false;
  40295. _this.ENVIRONMENTBRDF = false;
  40296. _this.NORMAL = false;
  40297. _this.TANGENT = false;
  40298. _this.BUMP = false;
  40299. _this.BUMPDIRECTUV = 0;
  40300. _this.OBJECTSPACE_NORMALMAP = false;
  40301. _this.PARALLAX = false;
  40302. _this.PARALLAXOCCLUSION = false;
  40303. _this.NORMALXYSCALE = true;
  40304. _this.LIGHTMAP = false;
  40305. _this.LIGHTMAPDIRECTUV = 0;
  40306. _this.USELIGHTMAPASSHADOWMAP = false;
  40307. _this.REFLECTION = false;
  40308. _this.REFLECTIONMAP_3D = false;
  40309. _this.REFLECTIONMAP_SPHERICAL = false;
  40310. _this.REFLECTIONMAP_PLANAR = false;
  40311. _this.REFLECTIONMAP_CUBIC = false;
  40312. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40313. _this.REFLECTIONMAP_PROJECTION = false;
  40314. _this.REFLECTIONMAP_SKYBOX = false;
  40315. _this.REFLECTIONMAP_EXPLICIT = false;
  40316. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40317. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40318. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40319. _this.INVERTCUBICMAP = false;
  40320. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40321. _this.USESPHERICALINVERTEX = false;
  40322. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40323. _this.LODINREFLECTIONALPHA = false;
  40324. _this.GAMMAREFLECTION = false;
  40325. _this.RADIANCEOCCLUSION = false;
  40326. _this.HORIZONOCCLUSION = false;
  40327. _this.REFRACTION = false;
  40328. _this.REFRACTIONMAP_3D = false;
  40329. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40330. _this.LODINREFRACTIONALPHA = false;
  40331. _this.GAMMAREFRACTION = false;
  40332. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40333. _this.INSTANCES = false;
  40334. _this.NUM_BONE_INFLUENCERS = 0;
  40335. _this.BonesPerMesh = 0;
  40336. _this.NONUNIFORMSCALING = false;
  40337. _this.MORPHTARGETS = false;
  40338. _this.MORPHTARGETS_NORMAL = false;
  40339. _this.MORPHTARGETS_TANGENT = false;
  40340. _this.NUM_MORPH_INFLUENCERS = 0;
  40341. _this.IMAGEPROCESSING = false;
  40342. _this.VIGNETTE = false;
  40343. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40344. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40345. _this.TONEMAPPING = false;
  40346. _this.CONTRAST = false;
  40347. _this.COLORCURVES = false;
  40348. _this.COLORGRADING = false;
  40349. _this.COLORGRADING3D = false;
  40350. _this.SAMPLER3DGREENDEPTH = false;
  40351. _this.SAMPLER3DBGRMAP = false;
  40352. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40353. _this.EXPOSURE = false;
  40354. _this.GRAIN = false;
  40355. _this.USEPHYSICALLIGHTFALLOFF = false;
  40356. _this.TWOSIDEDLIGHTING = false;
  40357. _this.SHADOWFLOAT = false;
  40358. _this.CLIPPLANE = false;
  40359. _this.POINTSIZE = false;
  40360. _this.FOG = false;
  40361. _this.LOGARITHMICDEPTH = false;
  40362. _this.FORCENORMALFORWARD = false;
  40363. _this.rebuild();
  40364. return _this;
  40365. }
  40366. /**
  40367. * Resets the PBR Material defines.
  40368. */
  40369. PBRMaterialDefines.prototype.reset = function () {
  40370. _super.prototype.reset.call(this);
  40371. this.ALPHATESTVALUE = 0.5;
  40372. this.PBR = true;
  40373. };
  40374. return PBRMaterialDefines;
  40375. }(BABYLON.MaterialDefines));
  40376. /**
  40377. * The Physically based material base class of BJS.
  40378. *
  40379. * This offers the main features of a standard PBR material.
  40380. * For more information, please refer to the documentation :
  40381. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40382. */
  40383. var PBRBaseMaterial = /** @class */ (function (_super) {
  40384. __extends(PBRBaseMaterial, _super);
  40385. /**
  40386. * Instantiates a new PBRMaterial instance.
  40387. *
  40388. * @param name The material name
  40389. * @param scene The scene the material will be use in.
  40390. */
  40391. function PBRBaseMaterial(name, scene) {
  40392. var _this = _super.call(this, name, scene) || this;
  40393. /**
  40394. * Intensity of the direct lights e.g. the four lights available in your scene.
  40395. * This impacts both the direct diffuse and specular highlights.
  40396. */
  40397. _this._directIntensity = 1.0;
  40398. /**
  40399. * Intensity of the emissive part of the material.
  40400. * This helps controlling the emissive effect without modifying the emissive color.
  40401. */
  40402. _this._emissiveIntensity = 1.0;
  40403. /**
  40404. * Intensity of the environment e.g. how much the environment will light the object
  40405. * either through harmonics for rough material or through the refelction for shiny ones.
  40406. */
  40407. _this._environmentIntensity = 1.0;
  40408. /**
  40409. * This is a special control allowing the reduction of the specular highlights coming from the
  40410. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40411. */
  40412. _this._specularIntensity = 1.0;
  40413. /**
  40414. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40415. */
  40416. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40417. /**
  40418. * Debug Control allowing disabling the bump map on this material.
  40419. */
  40420. _this._disableBumpMap = false;
  40421. /**
  40422. * AKA Occlusion Texture Intensity in other nomenclature.
  40423. */
  40424. _this._ambientTextureStrength = 1.0;
  40425. /**
  40426. * The color of a material in ambient lighting.
  40427. */
  40428. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40429. /**
  40430. * AKA Diffuse Color in other nomenclature.
  40431. */
  40432. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40433. /**
  40434. * AKA Specular Color in other nomenclature.
  40435. */
  40436. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40437. /**
  40438. * The color applied when light is reflected from a material.
  40439. */
  40440. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40441. /**
  40442. * The color applied when light is emitted from a material.
  40443. */
  40444. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40445. /**
  40446. * AKA Glossiness in other nomenclature.
  40447. */
  40448. _this._microSurface = 0.9;
  40449. /**
  40450. * source material index of refraction (IOR)' / 'destination material IOR.
  40451. */
  40452. _this._indexOfRefraction = 0.66;
  40453. /**
  40454. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40455. */
  40456. _this._invertRefractionY = false;
  40457. /**
  40458. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40459. * Materials half opaque for instance using refraction could benefit from this control.
  40460. */
  40461. _this._linkRefractionWithTransparency = false;
  40462. /**
  40463. * Specifies that the material will use the light map as a show map.
  40464. */
  40465. _this._useLightmapAsShadowmap = false;
  40466. /**
  40467. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40468. * makes the reflect vector face the model (under horizon).
  40469. */
  40470. _this._useHorizonOcclusion = true;
  40471. /**
  40472. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40473. * too much the area relying on ambient texture to define their ambient occlusion.
  40474. */
  40475. _this._useRadianceOcclusion = true;
  40476. /**
  40477. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40478. */
  40479. _this._useAlphaFromAlbedoTexture = false;
  40480. /**
  40481. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40482. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40483. */
  40484. _this._useSpecularOverAlpha = true;
  40485. /**
  40486. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40487. */
  40488. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40489. /**
  40490. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40491. */
  40492. _this._useRoughnessFromMetallicTextureAlpha = true;
  40493. /**
  40494. * Specifies if the metallic texture contains the roughness information in its green channel.
  40495. */
  40496. _this._useRoughnessFromMetallicTextureGreen = false;
  40497. /**
  40498. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40499. */
  40500. _this._useMetallnessFromMetallicTextureBlue = false;
  40501. /**
  40502. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40503. */
  40504. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40505. /**
  40506. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40507. */
  40508. _this._useAmbientInGrayScale = false;
  40509. /**
  40510. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40511. * The material will try to infer what glossiness each pixel should be.
  40512. */
  40513. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40514. /**
  40515. * BJS is using an harcoded light falloff based on a manually sets up range.
  40516. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40517. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40518. */
  40519. _this._usePhysicalLightFalloff = true;
  40520. /**
  40521. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40522. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40523. */
  40524. _this._useRadianceOverAlpha = true;
  40525. /**
  40526. * Allows using an object space normal map (instead of tangent space).
  40527. */
  40528. _this._useObjectSpaceNormalMap = false;
  40529. /**
  40530. * Allows using the bump map in parallax mode.
  40531. */
  40532. _this._useParallax = false;
  40533. /**
  40534. * Allows using the bump map in parallax occlusion mode.
  40535. */
  40536. _this._useParallaxOcclusion = false;
  40537. /**
  40538. * Controls the scale bias of the parallax mode.
  40539. */
  40540. _this._parallaxScaleBias = 0.05;
  40541. /**
  40542. * If sets to true, disables all the lights affecting the material.
  40543. */
  40544. _this._disableLighting = false;
  40545. /**
  40546. * Number of Simultaneous lights allowed on the material.
  40547. */
  40548. _this._maxSimultaneousLights = 4;
  40549. /**
  40550. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40551. */
  40552. _this._invertNormalMapX = false;
  40553. /**
  40554. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40555. */
  40556. _this._invertNormalMapY = false;
  40557. /**
  40558. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40559. */
  40560. _this._twoSidedLighting = false;
  40561. /**
  40562. * Defines the alpha limits in alpha test mode.
  40563. */
  40564. _this._alphaCutOff = 0.4;
  40565. /**
  40566. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40567. */
  40568. _this._forceAlphaTest = false;
  40569. /**
  40570. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40571. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40572. */
  40573. _this._useAlphaFresnel = false;
  40574. /**
  40575. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40576. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40577. */
  40578. _this._useLinearAlphaFresnel = false;
  40579. /**
  40580. * The transparency mode of the material.
  40581. */
  40582. _this._transparencyMode = null;
  40583. /**
  40584. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40585. * from cos thetav and roughness:
  40586. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40587. */
  40588. _this._environmentBRDFTexture = null;
  40589. /**
  40590. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40591. */
  40592. _this._forceIrradianceInFragment = false;
  40593. /**
  40594. * Force normal to face away from face.
  40595. */
  40596. _this._forceNormalForward = false;
  40597. /**
  40598. * Stores the available render targets.
  40599. */
  40600. _this._renderTargets = new BABYLON.SmartArray(16);
  40601. /**
  40602. * Sets the global ambient color for the material used in lighting calculations.
  40603. */
  40604. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40605. // Setup the default processing configuration to the scene.
  40606. _this._attachImageProcessingConfiguration(null);
  40607. _this.getRenderTargetTextures = function () {
  40608. _this._renderTargets.reset();
  40609. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40610. _this._renderTargets.push(_this._reflectionTexture);
  40611. }
  40612. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40613. _this._renderTargets.push(_this._refractionTexture);
  40614. }
  40615. return _this._renderTargets;
  40616. };
  40617. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40618. return _this;
  40619. }
  40620. /**
  40621. * Attaches a new image processing configuration to the PBR Material.
  40622. * @param configuration
  40623. */
  40624. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40625. var _this = this;
  40626. if (configuration === this._imageProcessingConfiguration) {
  40627. return;
  40628. }
  40629. // Detaches observer.
  40630. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40631. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40632. }
  40633. // Pick the scene configuration if needed.
  40634. if (!configuration) {
  40635. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40636. }
  40637. else {
  40638. this._imageProcessingConfiguration = configuration;
  40639. }
  40640. // Attaches observer.
  40641. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40642. _this._markAllSubMeshesAsImageProcessingDirty();
  40643. });
  40644. };
  40645. /**
  40646. * Gets the name of the material class.
  40647. */
  40648. PBRBaseMaterial.prototype.getClassName = function () {
  40649. return "PBRBaseMaterial";
  40650. };
  40651. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40652. /**
  40653. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40654. */
  40655. get: function () {
  40656. return this._useLogarithmicDepth;
  40657. },
  40658. /**
  40659. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40660. */
  40661. set: function (value) {
  40662. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40663. },
  40664. enumerable: true,
  40665. configurable: true
  40666. });
  40667. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40668. /**
  40669. * Gets the current transparency mode.
  40670. */
  40671. get: function () {
  40672. return this._transparencyMode;
  40673. },
  40674. /**
  40675. * Sets the transparency mode of the material.
  40676. */
  40677. set: function (value) {
  40678. if (this._transparencyMode === value) {
  40679. return;
  40680. }
  40681. this._transparencyMode = value;
  40682. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40683. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40684. },
  40685. enumerable: true,
  40686. configurable: true
  40687. });
  40688. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40689. /**
  40690. * Returns true if alpha blending should be disabled.
  40691. */
  40692. get: function () {
  40693. return (this._linkRefractionWithTransparency ||
  40694. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40695. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40696. },
  40697. enumerable: true,
  40698. configurable: true
  40699. });
  40700. /**
  40701. * Specifies whether or not this material should be rendered in alpha blend mode.
  40702. */
  40703. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40704. if (this._disableAlphaBlending) {
  40705. return false;
  40706. }
  40707. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40708. };
  40709. /**
  40710. * Specifies if the mesh will require alpha blending.
  40711. * @param mesh - BJS mesh.
  40712. */
  40713. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40714. if (this._disableAlphaBlending) {
  40715. return false;
  40716. }
  40717. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40718. };
  40719. /**
  40720. * Specifies whether or not this material should be rendered in alpha test mode.
  40721. */
  40722. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40723. if (this._forceAlphaTest) {
  40724. return true;
  40725. }
  40726. if (this._linkRefractionWithTransparency) {
  40727. return false;
  40728. }
  40729. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40730. };
  40731. /**
  40732. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40733. */
  40734. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40735. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40736. };
  40737. /**
  40738. * Gets the texture used for the alpha test.
  40739. */
  40740. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40741. return this._albedoTexture;
  40742. };
  40743. /**
  40744. * Specifies that the submesh is ready to be used.
  40745. * @param mesh - BJS mesh.
  40746. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40747. * @param useInstances - Specifies that instances should be used.
  40748. * @returns - boolean indicating that the submesh is ready or not.
  40749. */
  40750. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40751. if (subMesh.effect && this.isFrozen) {
  40752. if (this._wasPreviouslyReady) {
  40753. return true;
  40754. }
  40755. }
  40756. if (!subMesh._materialDefines) {
  40757. subMesh._materialDefines = new PBRMaterialDefines();
  40758. }
  40759. var defines = subMesh._materialDefines;
  40760. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40761. if (defines._renderId === this.getScene().getRenderId()) {
  40762. return true;
  40763. }
  40764. }
  40765. var scene = this.getScene();
  40766. var engine = scene.getEngine();
  40767. if (defines._areTexturesDirty) {
  40768. if (scene.texturesEnabled) {
  40769. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40770. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40771. return false;
  40772. }
  40773. }
  40774. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40775. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40776. return false;
  40777. }
  40778. }
  40779. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40780. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40781. return false;
  40782. }
  40783. }
  40784. var reflectionTexture = this._getReflectionTexture();
  40785. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40786. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40787. return false;
  40788. }
  40789. }
  40790. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40791. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40792. return false;
  40793. }
  40794. }
  40795. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40796. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40797. return false;
  40798. }
  40799. }
  40800. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40801. if (this._metallicTexture) {
  40802. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40803. return false;
  40804. }
  40805. }
  40806. else if (this._reflectivityTexture) {
  40807. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40808. return false;
  40809. }
  40810. }
  40811. if (this._microSurfaceTexture) {
  40812. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40813. return false;
  40814. }
  40815. }
  40816. }
  40817. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40818. // Bump texture cannot be not blocking.
  40819. if (!this._bumpTexture.isReady()) {
  40820. return false;
  40821. }
  40822. }
  40823. var refractionTexture = this._getRefractionTexture();
  40824. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40825. if (!refractionTexture.isReadyOrNotBlocking()) {
  40826. return false;
  40827. }
  40828. }
  40829. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40830. // This is blocking.
  40831. if (!this._environmentBRDFTexture.isReady()) {
  40832. return false;
  40833. }
  40834. }
  40835. }
  40836. }
  40837. if (defines._areImageProcessingDirty) {
  40838. if (!this._imageProcessingConfiguration.isReady()) {
  40839. return false;
  40840. }
  40841. }
  40842. if (!engine.getCaps().standardDerivatives) {
  40843. var bufferMesh = null;
  40844. if (mesh.getClassName() === "InstancedMesh") {
  40845. bufferMesh = mesh.sourceMesh;
  40846. }
  40847. else if (mesh.getClassName() === "Mesh") {
  40848. bufferMesh = mesh;
  40849. }
  40850. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40851. bufferMesh.createNormals(true);
  40852. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40853. }
  40854. }
  40855. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40856. if (effect) {
  40857. scene.resetCachedMaterial();
  40858. subMesh.setEffect(effect, defines);
  40859. this.buildUniformLayout();
  40860. }
  40861. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40862. return false;
  40863. }
  40864. defines._renderId = scene.getRenderId();
  40865. this._wasPreviouslyReady = true;
  40866. return true;
  40867. };
  40868. /**
  40869. * Specifies if the material uses metallic roughness workflow.
  40870. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40871. */
  40872. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40873. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40874. return true;
  40875. }
  40876. return false;
  40877. };
  40878. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40879. if (onCompiled === void 0) { onCompiled = null; }
  40880. if (onError === void 0) { onError = null; }
  40881. if (useInstances === void 0) { useInstances = null; }
  40882. if (useClipPlane === void 0) { useClipPlane = null; }
  40883. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40884. if (!defines.isDirty) {
  40885. return null;
  40886. }
  40887. defines.markAsProcessed();
  40888. var scene = this.getScene();
  40889. var engine = scene.getEngine();
  40890. // Fallbacks
  40891. var fallbacks = new BABYLON.EffectFallbacks();
  40892. var fallbackRank = 0;
  40893. if (defines.USESPHERICALINVERTEX) {
  40894. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40895. }
  40896. if (defines.FOG) {
  40897. fallbacks.addFallback(fallbackRank, "FOG");
  40898. }
  40899. if (defines.POINTSIZE) {
  40900. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40901. }
  40902. if (defines.LOGARITHMICDEPTH) {
  40903. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40904. }
  40905. if (defines.PARALLAX) {
  40906. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40907. }
  40908. if (defines.PARALLAXOCCLUSION) {
  40909. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40910. }
  40911. if (defines.ENVIRONMENTBRDF) {
  40912. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40913. }
  40914. if (defines.TANGENT) {
  40915. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40916. }
  40917. if (defines.BUMP) {
  40918. fallbacks.addFallback(fallbackRank++, "BUMP");
  40919. }
  40920. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40921. if (defines.SPECULARTERM) {
  40922. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40923. }
  40924. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40925. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40926. }
  40927. if (defines.LIGHTMAP) {
  40928. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40929. }
  40930. if (defines.NORMAL) {
  40931. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40932. }
  40933. if (defines.AMBIENT) {
  40934. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40935. }
  40936. if (defines.EMISSIVE) {
  40937. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40938. }
  40939. if (defines.VERTEXCOLOR) {
  40940. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40941. }
  40942. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40943. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40944. }
  40945. if (defines.MORPHTARGETS) {
  40946. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40947. }
  40948. //Attributes
  40949. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40950. if (defines.NORMAL) {
  40951. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40952. }
  40953. if (defines.TANGENT) {
  40954. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40955. }
  40956. if (defines.UV1) {
  40957. attribs.push(BABYLON.VertexBuffer.UVKind);
  40958. }
  40959. if (defines.UV2) {
  40960. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40961. }
  40962. if (defines.VERTEXCOLOR) {
  40963. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40964. }
  40965. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40966. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40967. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40968. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40969. "vFogInfos", "vFogColor", "pointSize",
  40970. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40971. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40972. "mBones",
  40973. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40974. "vLightingIntensity",
  40975. "logarithmicDepthConstant",
  40976. "vSphericalX", "vSphericalY", "vSphericalZ",
  40977. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40978. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40979. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40980. "vTangentSpaceParams"
  40981. ];
  40982. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40983. "bumpSampler", "lightmapSampler", "opacitySampler",
  40984. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40985. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40986. "microSurfaceSampler", "environmentBrdfSampler"];
  40987. var uniformBuffers = ["Material", "Scene"];
  40988. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40989. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40990. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40991. uniformsNames: uniforms,
  40992. uniformBuffersNames: uniformBuffers,
  40993. samplers: samplers,
  40994. defines: defines,
  40995. maxSimultaneousLights: this._maxSimultaneousLights
  40996. });
  40997. var join = defines.toString();
  40998. return engine.createEffect("pbr", {
  40999. attributes: attribs,
  41000. uniformsNames: uniforms,
  41001. uniformBuffersNames: uniformBuffers,
  41002. samplers: samplers,
  41003. defines: join,
  41004. fallbacks: fallbacks,
  41005. onCompiled: onCompiled,
  41006. onError: onError,
  41007. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41008. }, engine);
  41009. };
  41010. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41011. if (useInstances === void 0) { useInstances = null; }
  41012. if (useClipPlane === void 0) { useClipPlane = null; }
  41013. var scene = this.getScene();
  41014. var engine = scene.getEngine();
  41015. // Lights
  41016. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41017. defines._needNormals = true;
  41018. // Textures
  41019. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41020. if (defines._areTexturesDirty) {
  41021. defines._needUVs = false;
  41022. if (scene.texturesEnabled) {
  41023. if (scene.getEngine().getCaps().textureLOD) {
  41024. defines.LODBASEDMICROSFURACE = true;
  41025. }
  41026. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41027. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41028. }
  41029. else {
  41030. defines.ALBEDO = false;
  41031. }
  41032. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41034. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41035. }
  41036. else {
  41037. defines.AMBIENT = false;
  41038. }
  41039. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41041. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41042. }
  41043. else {
  41044. defines.OPACITY = false;
  41045. }
  41046. var reflectionTexture = this._getReflectionTexture();
  41047. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41048. defines.REFLECTION = true;
  41049. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41050. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41051. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41052. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41053. defines.INVERTCUBICMAP = true;
  41054. }
  41055. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41056. switch (reflectionTexture.coordinatesMode) {
  41057. case BABYLON.Texture.CUBIC_MODE:
  41058. case BABYLON.Texture.INVCUBIC_MODE:
  41059. defines.REFLECTIONMAP_CUBIC = true;
  41060. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41061. break;
  41062. case BABYLON.Texture.EXPLICIT_MODE:
  41063. defines.REFLECTIONMAP_EXPLICIT = true;
  41064. break;
  41065. case BABYLON.Texture.PLANAR_MODE:
  41066. defines.REFLECTIONMAP_PLANAR = true;
  41067. break;
  41068. case BABYLON.Texture.PROJECTION_MODE:
  41069. defines.REFLECTIONMAP_PROJECTION = true;
  41070. break;
  41071. case BABYLON.Texture.SKYBOX_MODE:
  41072. defines.REFLECTIONMAP_SKYBOX = true;
  41073. break;
  41074. case BABYLON.Texture.SPHERICAL_MODE:
  41075. defines.REFLECTIONMAP_SPHERICAL = true;
  41076. break;
  41077. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41078. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41079. break;
  41080. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41081. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41082. break;
  41083. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41084. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41085. break;
  41086. }
  41087. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41088. if (reflectionTexture.sphericalPolynomial) {
  41089. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41090. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41091. defines.USESPHERICALINVERTEX = false;
  41092. }
  41093. else {
  41094. defines.USESPHERICALINVERTEX = true;
  41095. }
  41096. }
  41097. }
  41098. }
  41099. else {
  41100. defines.REFLECTION = false;
  41101. defines.REFLECTIONMAP_3D = false;
  41102. defines.REFLECTIONMAP_SPHERICAL = false;
  41103. defines.REFLECTIONMAP_PLANAR = false;
  41104. defines.REFLECTIONMAP_CUBIC = false;
  41105. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41106. defines.REFLECTIONMAP_PROJECTION = false;
  41107. defines.REFLECTIONMAP_SKYBOX = false;
  41108. defines.REFLECTIONMAP_EXPLICIT = false;
  41109. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41110. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41111. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41112. defines.INVERTCUBICMAP = false;
  41113. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41114. defines.USESPHERICALINVERTEX = false;
  41115. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41116. defines.LODINREFLECTIONALPHA = false;
  41117. defines.GAMMAREFLECTION = false;
  41118. }
  41119. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41120. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41121. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41122. }
  41123. else {
  41124. defines.LIGHTMAP = false;
  41125. }
  41126. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41127. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41128. }
  41129. else {
  41130. defines.EMISSIVE = false;
  41131. }
  41132. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41133. if (this._metallicTexture) {
  41134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41135. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41136. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41137. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41138. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41139. }
  41140. else if (this._reflectivityTexture) {
  41141. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41142. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41143. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41144. }
  41145. else {
  41146. defines.REFLECTIVITY = false;
  41147. }
  41148. if (this._microSurfaceTexture) {
  41149. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41150. }
  41151. else {
  41152. defines.MICROSURFACEMAP = false;
  41153. }
  41154. }
  41155. else {
  41156. defines.REFLECTIVITY = false;
  41157. defines.MICROSURFACEMAP = false;
  41158. }
  41159. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41160. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41161. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41162. defines.PARALLAX = true;
  41163. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41164. }
  41165. else {
  41166. defines.PARALLAX = false;
  41167. }
  41168. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41169. }
  41170. else {
  41171. defines.BUMP = false;
  41172. }
  41173. var refractionTexture = this._getRefractionTexture();
  41174. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41175. defines.REFRACTION = true;
  41176. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41177. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41178. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41179. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41180. if (this._linkRefractionWithTransparency) {
  41181. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41182. }
  41183. }
  41184. else {
  41185. defines.REFRACTION = false;
  41186. }
  41187. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41188. defines.ENVIRONMENTBRDF = true;
  41189. }
  41190. else {
  41191. defines.ENVIRONMENTBRDF = false;
  41192. }
  41193. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41194. defines.ALPHAFROMALBEDO = true;
  41195. }
  41196. else {
  41197. defines.ALPHAFROMALBEDO = false;
  41198. }
  41199. }
  41200. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41201. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41202. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41203. if (!this.backFaceCulling && this._twoSidedLighting) {
  41204. defines.TWOSIDEDLIGHTING = true;
  41205. }
  41206. else {
  41207. defines.TWOSIDEDLIGHTING = false;
  41208. }
  41209. defines.ALPHATESTVALUE = this._alphaCutOff;
  41210. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41211. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41212. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41213. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41214. }
  41215. if (defines._areImageProcessingDirty) {
  41216. this._imageProcessingConfiguration.prepareDefines(defines);
  41217. }
  41218. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41219. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41220. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41221. // Misc.
  41222. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41223. // Values that need to be evaluated on every frame
  41224. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41225. // Attribs
  41226. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41227. };
  41228. /**
  41229. * Force shader compilation
  41230. */
  41231. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41232. var _this = this;
  41233. var localOptions = __assign({ clipPlane: false }, options);
  41234. var defines = new PBRMaterialDefines();
  41235. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41236. if (effect.isReady()) {
  41237. if (onCompiled) {
  41238. onCompiled(this);
  41239. }
  41240. }
  41241. else {
  41242. effect.onCompileObservable.add(function () {
  41243. if (onCompiled) {
  41244. onCompiled(_this);
  41245. }
  41246. });
  41247. }
  41248. };
  41249. /**
  41250. * Initializes the uniform buffer layout for the shader.
  41251. */
  41252. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41253. // Order is important !
  41254. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41255. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41256. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41257. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41258. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41259. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41260. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41261. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41262. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41263. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41264. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41265. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41266. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41267. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41268. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41269. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41270. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41271. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41272. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41273. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41274. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41275. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41276. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41277. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41278. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41279. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41280. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41281. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41282. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41283. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41284. this._uniformBuffer.addUniform("pointSize", 1);
  41285. this._uniformBuffer.create();
  41286. };
  41287. /**
  41288. * Unbinds the textures.
  41289. */
  41290. PBRBaseMaterial.prototype.unbind = function () {
  41291. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41292. this._uniformBuffer.setTexture("reflectionSampler", null);
  41293. }
  41294. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41295. this._uniformBuffer.setTexture("refractionSampler", null);
  41296. }
  41297. _super.prototype.unbind.call(this);
  41298. };
  41299. /**
  41300. * Binds the submesh data.
  41301. * @param world - The world matrix.
  41302. * @param mesh - The BJS mesh.
  41303. * @param subMesh - A submesh of the BJS mesh.
  41304. */
  41305. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41306. var scene = this.getScene();
  41307. var defines = subMesh._materialDefines;
  41308. if (!defines) {
  41309. return;
  41310. }
  41311. var effect = subMesh.effect;
  41312. if (!effect) {
  41313. return;
  41314. }
  41315. this._activeEffect = effect;
  41316. // Matrices
  41317. this.bindOnlyWorldMatrix(world);
  41318. // Normal Matrix
  41319. if (defines.OBJECTSPACE_NORMALMAP) {
  41320. world.toNormalMatrix(this._normalMatrix);
  41321. this.bindOnlyNormalMatrix(this._normalMatrix);
  41322. }
  41323. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41324. // Bones
  41325. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41326. var reflectionTexture = null;
  41327. if (mustRebind) {
  41328. this._uniformBuffer.bindToEffect(effect, "Material");
  41329. this.bindViewProjection(effect);
  41330. reflectionTexture = this._getReflectionTexture();
  41331. var refractionTexture = this._getRefractionTexture();
  41332. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41333. // Texture uniforms
  41334. if (scene.texturesEnabled) {
  41335. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41336. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41337. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41338. }
  41339. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41340. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41341. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41342. }
  41343. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41344. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41345. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41346. }
  41347. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41348. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41349. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41350. if (reflectionTexture.boundingBoxSize) {
  41351. var cubeTexture = reflectionTexture;
  41352. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41353. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41354. }
  41355. var polynomials = reflectionTexture.sphericalPolynomial;
  41356. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41357. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41358. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41359. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41360. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41361. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41362. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41363. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41364. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41365. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41366. }
  41367. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41368. }
  41369. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41370. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41371. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41372. }
  41373. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41374. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41375. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41376. }
  41377. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41378. if (this._metallicTexture) {
  41379. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41380. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41381. }
  41382. else if (this._reflectivityTexture) {
  41383. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41384. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41385. }
  41386. if (this._microSurfaceTexture) {
  41387. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41388. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41389. }
  41390. }
  41391. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41392. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41393. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41394. if (scene._mirroredCameraPosition) {
  41395. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41396. }
  41397. else {
  41398. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41399. }
  41400. }
  41401. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41402. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41403. var depth = 1.0;
  41404. if (!refractionTexture.isCube) {
  41405. if (refractionTexture.depth) {
  41406. depth = refractionTexture.depth;
  41407. }
  41408. }
  41409. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41410. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41411. }
  41412. }
  41413. // Point size
  41414. if (this.pointsCloud) {
  41415. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41416. }
  41417. // Colors
  41418. if (defines.METALLICWORKFLOW) {
  41419. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41420. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41421. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41422. }
  41423. else {
  41424. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41425. }
  41426. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41427. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41428. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41429. // Misc
  41430. this._lightingInfos.x = this._directIntensity;
  41431. this._lightingInfos.y = this._emissiveIntensity;
  41432. this._lightingInfos.z = this._environmentIntensity;
  41433. this._lightingInfos.w = this._specularIntensity;
  41434. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41435. }
  41436. // Textures
  41437. if (scene.texturesEnabled) {
  41438. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41439. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41440. }
  41441. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41442. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41443. }
  41444. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41445. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41446. }
  41447. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41448. if (defines.LODBASEDMICROSFURACE) {
  41449. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41450. }
  41451. else {
  41452. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41453. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41454. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41455. }
  41456. }
  41457. if (defines.ENVIRONMENTBRDF) {
  41458. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41459. }
  41460. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41461. if (defines.LODBASEDMICROSFURACE) {
  41462. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41463. }
  41464. else {
  41465. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41466. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41467. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41468. }
  41469. }
  41470. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41471. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41472. }
  41473. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41474. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41475. }
  41476. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41477. if (this._metallicTexture) {
  41478. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41479. }
  41480. else if (this._reflectivityTexture) {
  41481. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41482. }
  41483. if (this._microSurfaceTexture) {
  41484. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41485. }
  41486. }
  41487. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41488. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41489. }
  41490. }
  41491. // Clip plane
  41492. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41493. // Colors
  41494. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41495. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41496. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41497. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41498. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41499. }
  41500. if (mustRebind || !this.isFrozen) {
  41501. // Lights
  41502. if (scene.lightsEnabled && !this._disableLighting) {
  41503. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41504. }
  41505. // View
  41506. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41507. this.bindView(effect);
  41508. }
  41509. // Fog
  41510. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41511. // Morph targets
  41512. if (defines.NUM_MORPH_INFLUENCERS) {
  41513. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41514. }
  41515. // image processing
  41516. this._imageProcessingConfiguration.bind(this._activeEffect);
  41517. // Log. depth
  41518. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41519. }
  41520. this._uniformBuffer.update();
  41521. this._afterBind(mesh);
  41522. };
  41523. /**
  41524. * Returns the animatable textures.
  41525. * @returns - Array of animatable textures.
  41526. */
  41527. PBRBaseMaterial.prototype.getAnimatables = function () {
  41528. var results = [];
  41529. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41530. results.push(this._albedoTexture);
  41531. }
  41532. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41533. results.push(this._ambientTexture);
  41534. }
  41535. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41536. results.push(this._opacityTexture);
  41537. }
  41538. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41539. results.push(this._reflectionTexture);
  41540. }
  41541. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41542. results.push(this._emissiveTexture);
  41543. }
  41544. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41545. results.push(this._metallicTexture);
  41546. }
  41547. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41548. results.push(this._reflectivityTexture);
  41549. }
  41550. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41551. results.push(this._bumpTexture);
  41552. }
  41553. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41554. results.push(this._lightmapTexture);
  41555. }
  41556. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41557. results.push(this._refractionTexture);
  41558. }
  41559. return results;
  41560. };
  41561. /**
  41562. * Returns the texture used for reflections.
  41563. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41564. */
  41565. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41566. if (this._reflectionTexture) {
  41567. return this._reflectionTexture;
  41568. }
  41569. return this.getScene().environmentTexture;
  41570. };
  41571. /**
  41572. * Returns the texture used for refraction or null if none is used.
  41573. * @returns - Refection texture if present. If no refraction texture and refraction
  41574. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41575. */
  41576. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41577. if (this._refractionTexture) {
  41578. return this._refractionTexture;
  41579. }
  41580. if (this._linkRefractionWithTransparency) {
  41581. return this.getScene().environmentTexture;
  41582. }
  41583. return null;
  41584. };
  41585. /**
  41586. * Disposes the resources of the material.
  41587. * @param forceDisposeEffect - Forces the disposal of effects.
  41588. * @param forceDisposeTextures - Forces the disposal of all textures.
  41589. */
  41590. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41591. if (forceDisposeTextures) {
  41592. if (this._albedoTexture) {
  41593. this._albedoTexture.dispose();
  41594. }
  41595. if (this._ambientTexture) {
  41596. this._ambientTexture.dispose();
  41597. }
  41598. if (this._opacityTexture) {
  41599. this._opacityTexture.dispose();
  41600. }
  41601. if (this._reflectionTexture) {
  41602. this._reflectionTexture.dispose();
  41603. }
  41604. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41605. this._environmentBRDFTexture.dispose();
  41606. }
  41607. if (this._emissiveTexture) {
  41608. this._emissiveTexture.dispose();
  41609. }
  41610. if (this._metallicTexture) {
  41611. this._metallicTexture.dispose();
  41612. }
  41613. if (this._reflectivityTexture) {
  41614. this._reflectivityTexture.dispose();
  41615. }
  41616. if (this._bumpTexture) {
  41617. this._bumpTexture.dispose();
  41618. }
  41619. if (this._lightmapTexture) {
  41620. this._lightmapTexture.dispose();
  41621. }
  41622. if (this._refractionTexture) {
  41623. this._refractionTexture.dispose();
  41624. }
  41625. }
  41626. this._renderTargets.dispose();
  41627. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41628. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41629. }
  41630. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41631. };
  41632. /**
  41633. * Stores the reflectivity values based on metallic roughness workflow.
  41634. */
  41635. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41636. __decorate([
  41637. BABYLON.serializeAsImageProcessingConfiguration()
  41638. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41639. __decorate([
  41640. BABYLON.serialize()
  41641. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41642. __decorate([
  41643. BABYLON.serialize()
  41644. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41645. return PBRBaseMaterial;
  41646. }(BABYLON.PushMaterial));
  41647. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41648. })(BABYLON || (BABYLON = {}));
  41649. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41650. var BABYLON;
  41651. (function (BABYLON) {
  41652. /**
  41653. * The Physically based simple base material of BJS.
  41654. *
  41655. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41656. * It is used as the base class for both the specGloss and metalRough conventions.
  41657. */
  41658. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41659. __extends(PBRBaseSimpleMaterial, _super);
  41660. /**
  41661. * Instantiates a new PBRMaterial instance.
  41662. *
  41663. * @param name The material name
  41664. * @param scene The scene the material will be use in.
  41665. */
  41666. function PBRBaseSimpleMaterial(name, scene) {
  41667. var _this = _super.call(this, name, scene) || this;
  41668. /**
  41669. * Number of Simultaneous lights allowed on the material.
  41670. */
  41671. _this.maxSimultaneousLights = 4;
  41672. /**
  41673. * If sets to true, disables all the lights affecting the material.
  41674. */
  41675. _this.disableLighting = false;
  41676. /**
  41677. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41678. */
  41679. _this.invertNormalMapX = false;
  41680. /**
  41681. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41682. */
  41683. _this.invertNormalMapY = false;
  41684. /**
  41685. * Emissivie color used to self-illuminate the model.
  41686. */
  41687. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41688. /**
  41689. * Occlusion Channel Strenght.
  41690. */
  41691. _this.occlusionStrength = 1.0;
  41692. _this.useLightmapAsShadowmap = false;
  41693. _this._useAlphaFromAlbedoTexture = true;
  41694. _this._useAmbientInGrayScale = true;
  41695. return _this;
  41696. }
  41697. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41698. /**
  41699. * Gets the current double sided mode.
  41700. */
  41701. get: function () {
  41702. return this._twoSidedLighting;
  41703. },
  41704. /**
  41705. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41706. */
  41707. set: function (value) {
  41708. if (this._twoSidedLighting === value) {
  41709. return;
  41710. }
  41711. this._twoSidedLighting = value;
  41712. this.backFaceCulling = !value;
  41713. this._markAllSubMeshesAsTexturesDirty();
  41714. },
  41715. enumerable: true,
  41716. configurable: true
  41717. });
  41718. /**
  41719. * Return the active textures of the material.
  41720. */
  41721. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41722. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41723. if (this.environmentTexture) {
  41724. activeTextures.push(this.environmentTexture);
  41725. }
  41726. if (this.normalTexture) {
  41727. activeTextures.push(this.normalTexture);
  41728. }
  41729. if (this.emissiveTexture) {
  41730. activeTextures.push(this.emissiveTexture);
  41731. }
  41732. if (this.occlusionTexture) {
  41733. activeTextures.push(this.occlusionTexture);
  41734. }
  41735. if (this.lightmapTexture) {
  41736. activeTextures.push(this.lightmapTexture);
  41737. }
  41738. return activeTextures;
  41739. };
  41740. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41741. if (_super.prototype.hasTexture.call(this, texture)) {
  41742. return true;
  41743. }
  41744. if (this.lightmapTexture === texture) {
  41745. return true;
  41746. }
  41747. return false;
  41748. };
  41749. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41750. return "PBRBaseSimpleMaterial";
  41751. };
  41752. __decorate([
  41753. BABYLON.serialize(),
  41754. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41755. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41756. __decorate([
  41757. BABYLON.serialize(),
  41758. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41759. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41760. __decorate([
  41761. BABYLON.serializeAsTexture(),
  41762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41763. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41764. __decorate([
  41765. BABYLON.serialize(),
  41766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41767. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41768. __decorate([
  41769. BABYLON.serialize(),
  41770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41771. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41772. __decorate([
  41773. BABYLON.serializeAsTexture(),
  41774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41775. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41776. __decorate([
  41777. BABYLON.serializeAsColor3("emissive"),
  41778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41779. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41780. __decorate([
  41781. BABYLON.serializeAsTexture(),
  41782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41783. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41784. __decorate([
  41785. BABYLON.serialize(),
  41786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41787. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41788. __decorate([
  41789. BABYLON.serializeAsTexture(),
  41790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41791. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41792. __decorate([
  41793. BABYLON.serialize(),
  41794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41795. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41796. __decorate([
  41797. BABYLON.serialize()
  41798. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41799. __decorate([
  41800. BABYLON.serializeAsTexture(),
  41801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41802. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41803. __decorate([
  41804. BABYLON.serialize(),
  41805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41806. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41807. return PBRBaseSimpleMaterial;
  41808. }(BABYLON.PBRBaseMaterial));
  41809. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41810. })(BABYLON || (BABYLON = {}));
  41811. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41812. var BABYLON;
  41813. (function (BABYLON) {
  41814. /**
  41815. * The Physically based material of BJS.
  41816. *
  41817. * This offers the main features of a standard PBR material.
  41818. * For more information, please refer to the documentation :
  41819. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41820. */
  41821. var PBRMaterial = /** @class */ (function (_super) {
  41822. __extends(PBRMaterial, _super);
  41823. /**
  41824. * Instantiates a new PBRMaterial instance.
  41825. *
  41826. * @param name The material name
  41827. * @param scene The scene the material will be use in.
  41828. */
  41829. function PBRMaterial(name, scene) {
  41830. var _this = _super.call(this, name, scene) || this;
  41831. /**
  41832. * Intensity of the direct lights e.g. the four lights available in your scene.
  41833. * This impacts both the direct diffuse and specular highlights.
  41834. */
  41835. _this.directIntensity = 1.0;
  41836. /**
  41837. * Intensity of the emissive part of the material.
  41838. * This helps controlling the emissive effect without modifying the emissive color.
  41839. */
  41840. _this.emissiveIntensity = 1.0;
  41841. /**
  41842. * Intensity of the environment e.g. how much the environment will light the object
  41843. * either through harmonics for rough material or through the refelction for shiny ones.
  41844. */
  41845. _this.environmentIntensity = 1.0;
  41846. /**
  41847. * This is a special control allowing the reduction of the specular highlights coming from the
  41848. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41849. */
  41850. _this.specularIntensity = 1.0;
  41851. /**
  41852. * Debug Control allowing disabling the bump map on this material.
  41853. */
  41854. _this.disableBumpMap = false;
  41855. /**
  41856. * AKA Occlusion Texture Intensity in other nomenclature.
  41857. */
  41858. _this.ambientTextureStrength = 1.0;
  41859. /**
  41860. * The color of a material in ambient lighting.
  41861. */
  41862. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41863. /**
  41864. * AKA Diffuse Color in other nomenclature.
  41865. */
  41866. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41867. /**
  41868. * AKA Specular Color in other nomenclature.
  41869. */
  41870. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41871. /**
  41872. * The color reflected from the material.
  41873. */
  41874. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41875. /**
  41876. * The color emitted from the material.
  41877. */
  41878. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41879. /**
  41880. * AKA Glossiness in other nomenclature.
  41881. */
  41882. _this.microSurface = 1.0;
  41883. /**
  41884. * source material index of refraction (IOR)' / 'destination material IOR.
  41885. */
  41886. _this.indexOfRefraction = 0.66;
  41887. /**
  41888. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41889. */
  41890. _this.invertRefractionY = false;
  41891. /**
  41892. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41893. * Materials half opaque for instance using refraction could benefit from this control.
  41894. */
  41895. _this.linkRefractionWithTransparency = false;
  41896. _this.useLightmapAsShadowmap = false;
  41897. /**
  41898. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41899. */
  41900. _this.useAlphaFromAlbedoTexture = false;
  41901. /**
  41902. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41903. */
  41904. _this.forceAlphaTest = false;
  41905. /**
  41906. * Defines the alpha limits in alpha test mode.
  41907. */
  41908. _this.alphaCutOff = 0.4;
  41909. /**
  41910. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41911. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41912. */
  41913. _this.useSpecularOverAlpha = true;
  41914. /**
  41915. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41916. */
  41917. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41918. /**
  41919. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41920. */
  41921. _this.useRoughnessFromMetallicTextureAlpha = true;
  41922. /**
  41923. * Specifies if the metallic texture contains the roughness information in its green channel.
  41924. */
  41925. _this.useRoughnessFromMetallicTextureGreen = false;
  41926. /**
  41927. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41928. */
  41929. _this.useMetallnessFromMetallicTextureBlue = false;
  41930. /**
  41931. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41932. */
  41933. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41934. /**
  41935. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41936. */
  41937. _this.useAmbientInGrayScale = false;
  41938. /**
  41939. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41940. * The material will try to infer what glossiness each pixel should be.
  41941. */
  41942. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41943. /**
  41944. * BJS is using an harcoded light falloff based on a manually sets up range.
  41945. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41946. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41947. */
  41948. _this.usePhysicalLightFalloff = true;
  41949. /**
  41950. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41951. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41952. */
  41953. _this.useRadianceOverAlpha = true;
  41954. /**
  41955. * Allows using an object space normal map (instead of tangent space).
  41956. */
  41957. _this.useObjectSpaceNormalMap = false;
  41958. /**
  41959. * Allows using the bump map in parallax mode.
  41960. */
  41961. _this.useParallax = false;
  41962. /**
  41963. * Allows using the bump map in parallax occlusion mode.
  41964. */
  41965. _this.useParallaxOcclusion = false;
  41966. /**
  41967. * Controls the scale bias of the parallax mode.
  41968. */
  41969. _this.parallaxScaleBias = 0.05;
  41970. /**
  41971. * If sets to true, disables all the lights affecting the material.
  41972. */
  41973. _this.disableLighting = false;
  41974. /**
  41975. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41976. */
  41977. _this.forceIrradianceInFragment = false;
  41978. /**
  41979. * Number of Simultaneous lights allowed on the material.
  41980. */
  41981. _this.maxSimultaneousLights = 4;
  41982. /**
  41983. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41984. */
  41985. _this.invertNormalMapX = false;
  41986. /**
  41987. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41988. */
  41989. _this.invertNormalMapY = false;
  41990. /**
  41991. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41992. */
  41993. _this.twoSidedLighting = false;
  41994. /**
  41995. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41996. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41997. */
  41998. _this.useAlphaFresnel = false;
  41999. /**
  42000. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42001. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42002. */
  42003. _this.useLinearAlphaFresnel = false;
  42004. /**
  42005. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42006. * And/Or occlude the blended part.
  42007. */
  42008. _this.environmentBRDFTexture = null;
  42009. /**
  42010. * Force normal to face away from face.
  42011. */
  42012. _this.forceNormalForward = false;
  42013. /**
  42014. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42015. * makes the reflect vector face the model (under horizon).
  42016. */
  42017. _this.useHorizonOcclusion = true;
  42018. /**
  42019. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42020. * too much the area relying on ambient texture to define their ambient occlusion.
  42021. */
  42022. _this.useRadianceOcclusion = true;
  42023. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42024. return _this;
  42025. }
  42026. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42027. /**
  42028. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42029. */
  42030. get: function () {
  42031. return this._PBRMATERIAL_OPAQUE;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42037. /**
  42038. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42039. */
  42040. get: function () {
  42041. return this._PBRMATERIAL_ALPHATEST;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42047. /**
  42048. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42049. */
  42050. get: function () {
  42051. return this._PBRMATERIAL_ALPHABLEND;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42057. /**
  42058. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42059. * They are also discarded below the alpha cutoff threshold to improve performances.
  42060. */
  42061. get: function () {
  42062. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42063. },
  42064. enumerable: true,
  42065. configurable: true
  42066. });
  42067. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42068. /**
  42069. * Gets the image processing configuration used either in this material.
  42070. */
  42071. get: function () {
  42072. return this._imageProcessingConfiguration;
  42073. },
  42074. /**
  42075. * Sets the Default image processing configuration used either in the this material.
  42076. *
  42077. * If sets to null, the scene one is in use.
  42078. */
  42079. set: function (value) {
  42080. this._attachImageProcessingConfiguration(value);
  42081. // Ensure the effect will be rebuilt.
  42082. this._markAllSubMeshesAsTexturesDirty();
  42083. },
  42084. enumerable: true,
  42085. configurable: true
  42086. });
  42087. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42088. /**
  42089. * Gets wether the color curves effect is enabled.
  42090. */
  42091. get: function () {
  42092. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42093. },
  42094. /**
  42095. * Sets wether the color curves effect is enabled.
  42096. */
  42097. set: function (value) {
  42098. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42099. },
  42100. enumerable: true,
  42101. configurable: true
  42102. });
  42103. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42104. /**
  42105. * Gets wether the color grading effect is enabled.
  42106. */
  42107. get: function () {
  42108. return this.imageProcessingConfiguration.colorGradingEnabled;
  42109. },
  42110. /**
  42111. * Gets wether the color grading effect is enabled.
  42112. */
  42113. set: function (value) {
  42114. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42120. /**
  42121. * Gets wether tonemapping is enabled or not.
  42122. */
  42123. get: function () {
  42124. return this._imageProcessingConfiguration.toneMappingEnabled;
  42125. },
  42126. /**
  42127. * Sets wether tonemapping is enabled or not
  42128. */
  42129. set: function (value) {
  42130. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. ;
  42136. ;
  42137. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42138. /**
  42139. * The camera exposure used on this material.
  42140. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42141. * This corresponds to a photographic exposure.
  42142. */
  42143. get: function () {
  42144. return this._imageProcessingConfiguration.exposure;
  42145. },
  42146. /**
  42147. * The camera exposure used on this material.
  42148. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42149. * This corresponds to a photographic exposure.
  42150. */
  42151. set: function (value) {
  42152. this._imageProcessingConfiguration.exposure = value;
  42153. },
  42154. enumerable: true,
  42155. configurable: true
  42156. });
  42157. ;
  42158. ;
  42159. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42160. /**
  42161. * Gets The camera contrast used on this material.
  42162. */
  42163. get: function () {
  42164. return this._imageProcessingConfiguration.contrast;
  42165. },
  42166. /**
  42167. * Sets The camera contrast used on this material.
  42168. */
  42169. set: function (value) {
  42170. this._imageProcessingConfiguration.contrast = value;
  42171. },
  42172. enumerable: true,
  42173. configurable: true
  42174. });
  42175. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42176. /**
  42177. * Gets the Color Grading 2D Lookup Texture.
  42178. */
  42179. get: function () {
  42180. return this._imageProcessingConfiguration.colorGradingTexture;
  42181. },
  42182. /**
  42183. * Sets the Color Grading 2D Lookup Texture.
  42184. */
  42185. set: function (value) {
  42186. this._imageProcessingConfiguration.colorGradingTexture = value;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42192. /**
  42193. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42194. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42195. * 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;
  42196. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42197. */
  42198. get: function () {
  42199. return this._imageProcessingConfiguration.colorCurves;
  42200. },
  42201. /**
  42202. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42203. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42204. * 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;
  42205. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42206. */
  42207. set: function (value) {
  42208. this._imageProcessingConfiguration.colorCurves = value;
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. /**
  42214. * Returns the name of this material class.
  42215. */
  42216. PBRMaterial.prototype.getClassName = function () {
  42217. return "PBRMaterial";
  42218. };
  42219. /**
  42220. * Returns an array of the actively used textures.
  42221. * @returns - Array of BaseTextures
  42222. */
  42223. PBRMaterial.prototype.getActiveTextures = function () {
  42224. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42225. if (this._albedoTexture) {
  42226. activeTextures.push(this._albedoTexture);
  42227. }
  42228. if (this._ambientTexture) {
  42229. activeTextures.push(this._ambientTexture);
  42230. }
  42231. if (this._opacityTexture) {
  42232. activeTextures.push(this._opacityTexture);
  42233. }
  42234. if (this._reflectionTexture) {
  42235. activeTextures.push(this._reflectionTexture);
  42236. }
  42237. if (this._emissiveTexture) {
  42238. activeTextures.push(this._emissiveTexture);
  42239. }
  42240. if (this._reflectivityTexture) {
  42241. activeTextures.push(this._reflectivityTexture);
  42242. }
  42243. if (this._metallicTexture) {
  42244. activeTextures.push(this._metallicTexture);
  42245. }
  42246. if (this._microSurfaceTexture) {
  42247. activeTextures.push(this._microSurfaceTexture);
  42248. }
  42249. if (this._bumpTexture) {
  42250. activeTextures.push(this._bumpTexture);
  42251. }
  42252. if (this._lightmapTexture) {
  42253. activeTextures.push(this._lightmapTexture);
  42254. }
  42255. if (this._refractionTexture) {
  42256. activeTextures.push(this._refractionTexture);
  42257. }
  42258. return activeTextures;
  42259. };
  42260. /**
  42261. * Checks to see if a texture is used in the material.
  42262. * @param texture - Base texture to use.
  42263. * @returns - Boolean specifying if a texture is used in the material.
  42264. */
  42265. PBRMaterial.prototype.hasTexture = function (texture) {
  42266. if (_super.prototype.hasTexture.call(this, texture)) {
  42267. return true;
  42268. }
  42269. if (this._albedoTexture === texture) {
  42270. return true;
  42271. }
  42272. if (this._ambientTexture === texture) {
  42273. return true;
  42274. }
  42275. if (this._opacityTexture === texture) {
  42276. return true;
  42277. }
  42278. if (this._reflectionTexture === texture) {
  42279. return true;
  42280. }
  42281. if (this._reflectivityTexture === texture) {
  42282. return true;
  42283. }
  42284. if (this._metallicTexture === texture) {
  42285. return true;
  42286. }
  42287. if (this._microSurfaceTexture === texture) {
  42288. return true;
  42289. }
  42290. if (this._bumpTexture === texture) {
  42291. return true;
  42292. }
  42293. if (this._lightmapTexture === texture) {
  42294. return true;
  42295. }
  42296. if (this._refractionTexture === texture) {
  42297. return true;
  42298. }
  42299. return false;
  42300. };
  42301. /**
  42302. * Makes a duplicate of the current material.
  42303. * @param name - name to use for the new material.
  42304. */
  42305. PBRMaterial.prototype.clone = function (name) {
  42306. var _this = this;
  42307. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42308. clone.id = name;
  42309. clone.name = name;
  42310. return clone;
  42311. };
  42312. /**
  42313. * Serializes this PBR Material.
  42314. * @returns - An object with the serialized material.
  42315. */
  42316. PBRMaterial.prototype.serialize = function () {
  42317. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42318. serializationObject.customType = "BABYLON.PBRMaterial";
  42319. return serializationObject;
  42320. };
  42321. // Statics
  42322. /**
  42323. * Parses a PBR Material from a serialized object.
  42324. * @param source - Serialized object.
  42325. * @param scene - BJS scene instance.
  42326. * @param rootUrl - url for the scene object
  42327. * @returns - PBRMaterial
  42328. */
  42329. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42330. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42331. };
  42332. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42333. /**
  42334. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42335. */
  42336. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42337. /**
  42338. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42339. */
  42340. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42341. /**
  42342. * 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.
  42343. * They are also discarded below the alpha cutoff threshold to improve performances.
  42344. */
  42345. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42346. __decorate([
  42347. BABYLON.serialize(),
  42348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42349. ], PBRMaterial.prototype, "directIntensity", void 0);
  42350. __decorate([
  42351. BABYLON.serialize(),
  42352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42353. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42354. __decorate([
  42355. BABYLON.serialize(),
  42356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42357. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42358. __decorate([
  42359. BABYLON.serialize(),
  42360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42361. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42362. __decorate([
  42363. BABYLON.serialize(),
  42364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42365. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42366. __decorate([
  42367. BABYLON.serializeAsTexture(),
  42368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42369. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42370. __decorate([
  42371. BABYLON.serializeAsTexture(),
  42372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42373. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42374. __decorate([
  42375. BABYLON.serialize(),
  42376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42377. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42378. __decorate([
  42379. BABYLON.serializeAsTexture(),
  42380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42381. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42382. __decorate([
  42383. BABYLON.serializeAsTexture(),
  42384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42385. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42386. __decorate([
  42387. BABYLON.serializeAsTexture(),
  42388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42389. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42390. __decorate([
  42391. BABYLON.serializeAsTexture(),
  42392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42393. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42394. __decorate([
  42395. BABYLON.serializeAsTexture(),
  42396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42397. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42398. __decorate([
  42399. BABYLON.serialize(),
  42400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42401. ], PBRMaterial.prototype, "metallic", void 0);
  42402. __decorate([
  42403. BABYLON.serialize(),
  42404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42405. ], PBRMaterial.prototype, "roughness", void 0);
  42406. __decorate([
  42407. BABYLON.serializeAsTexture(),
  42408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42409. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42410. __decorate([
  42411. BABYLON.serializeAsTexture(),
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42413. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42414. __decorate([
  42415. BABYLON.serializeAsTexture(),
  42416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42417. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42418. __decorate([
  42419. BABYLON.serializeAsTexture(),
  42420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42421. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42422. __decorate([
  42423. BABYLON.serializeAsColor3("ambient"),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], PBRMaterial.prototype, "ambientColor", void 0);
  42426. __decorate([
  42427. BABYLON.serializeAsColor3("albedo"),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42429. ], PBRMaterial.prototype, "albedoColor", void 0);
  42430. __decorate([
  42431. BABYLON.serializeAsColor3("reflectivity"),
  42432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42433. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42434. __decorate([
  42435. BABYLON.serializeAsColor3("reflection"),
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42438. __decorate([
  42439. BABYLON.serializeAsColor3("emissive"),
  42440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42441. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42442. __decorate([
  42443. BABYLON.serialize(),
  42444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42445. ], PBRMaterial.prototype, "microSurface", void 0);
  42446. __decorate([
  42447. BABYLON.serialize(),
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42449. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42450. __decorate([
  42451. BABYLON.serialize(),
  42452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42453. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42454. __decorate([
  42455. BABYLON.serialize(),
  42456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42457. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42458. __decorate([
  42459. BABYLON.serialize(),
  42460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42461. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42462. __decorate([
  42463. BABYLON.serialize(),
  42464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42465. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42466. __decorate([
  42467. BABYLON.serialize(),
  42468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42469. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42470. __decorate([
  42471. BABYLON.serialize(),
  42472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42473. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42474. __decorate([
  42475. BABYLON.serialize(),
  42476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42477. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42478. __decorate([
  42479. BABYLON.serialize(),
  42480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42481. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42482. __decorate([
  42483. BABYLON.serialize(),
  42484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42485. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42486. __decorate([
  42487. BABYLON.serialize(),
  42488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42489. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42490. __decorate([
  42491. BABYLON.serialize(),
  42492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42493. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42494. __decorate([
  42495. BABYLON.serialize(),
  42496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42497. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42498. __decorate([
  42499. BABYLON.serialize(),
  42500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42501. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42502. __decorate([
  42503. BABYLON.serialize(),
  42504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42505. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42506. __decorate([
  42507. BABYLON.serialize(),
  42508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42509. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42510. __decorate([
  42511. BABYLON.serialize(),
  42512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42513. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42514. __decorate([
  42515. BABYLON.serialize(),
  42516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42517. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42518. __decorate([
  42519. BABYLON.serialize(),
  42520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42521. ], PBRMaterial.prototype, "useParallax", void 0);
  42522. __decorate([
  42523. BABYLON.serialize(),
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42525. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42526. __decorate([
  42527. BABYLON.serialize(),
  42528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42529. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42530. __decorate([
  42531. BABYLON.serialize(),
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42533. ], PBRMaterial.prototype, "disableLighting", void 0);
  42534. __decorate([
  42535. BABYLON.serialize(),
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42537. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42538. __decorate([
  42539. BABYLON.serialize(),
  42540. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42541. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42542. __decorate([
  42543. BABYLON.serialize(),
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42545. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42546. __decorate([
  42547. BABYLON.serialize(),
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42549. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42550. __decorate([
  42551. BABYLON.serialize(),
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42554. __decorate([
  42555. BABYLON.serialize(),
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42557. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42558. __decorate([
  42559. BABYLON.serialize(),
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42561. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42562. __decorate([
  42563. BABYLON.serializeAsTexture(),
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42566. __decorate([
  42567. BABYLON.serialize(),
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42569. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42570. __decorate([
  42571. BABYLON.serialize(),
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42573. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42574. __decorate([
  42575. BABYLON.serialize(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42577. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42578. return PBRMaterial;
  42579. }(BABYLON.PBRBaseMaterial));
  42580. BABYLON.PBRMaterial = PBRMaterial;
  42581. })(BABYLON || (BABYLON = {}));
  42582. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42583. var BABYLON;
  42584. (function (BABYLON) {
  42585. /**
  42586. * The PBR material of BJS following the metal roughness convention.
  42587. *
  42588. * This fits to the PBR convention in the GLTF definition:
  42589. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42590. */
  42591. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42592. __extends(PBRMetallicRoughnessMaterial, _super);
  42593. /**
  42594. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42595. *
  42596. * @param name The material name
  42597. * @param scene The scene the material will be use in.
  42598. */
  42599. function PBRMetallicRoughnessMaterial(name, scene) {
  42600. var _this = _super.call(this, name, scene) || this;
  42601. _this._useRoughnessFromMetallicTextureAlpha = false;
  42602. _this._useRoughnessFromMetallicTextureGreen = true;
  42603. _this._useMetallnessFromMetallicTextureBlue = true;
  42604. _this.metallic = 1.0;
  42605. _this.roughness = 1.0;
  42606. return _this;
  42607. }
  42608. /**
  42609. * Return the currrent class name of the material.
  42610. */
  42611. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42612. return "PBRMetallicRoughnessMaterial";
  42613. };
  42614. /**
  42615. * Return the active textures of the material.
  42616. */
  42617. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42618. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42619. if (this.baseTexture) {
  42620. activeTextures.push(this.baseTexture);
  42621. }
  42622. if (this.metallicRoughnessTexture) {
  42623. activeTextures.push(this.metallicRoughnessTexture);
  42624. }
  42625. return activeTextures;
  42626. };
  42627. /**
  42628. * Checks to see if a texture is used in the material.
  42629. * @param texture - Base texture to use.
  42630. * @returns - Boolean specifying if a texture is used in the material.
  42631. */
  42632. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42633. if (_super.prototype.hasTexture.call(this, texture)) {
  42634. return true;
  42635. }
  42636. if (this.baseTexture === texture) {
  42637. return true;
  42638. }
  42639. if (this.metallicRoughnessTexture === texture) {
  42640. return true;
  42641. }
  42642. return false;
  42643. };
  42644. /**
  42645. * Makes a duplicate of the current material.
  42646. * @param name - name to use for the new material.
  42647. */
  42648. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42649. var _this = this;
  42650. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42651. clone.id = name;
  42652. clone.name = name;
  42653. return clone;
  42654. };
  42655. /**
  42656. * Serialize the material to a parsable JSON object.
  42657. */
  42658. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42659. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42660. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42661. return serializationObject;
  42662. };
  42663. /**
  42664. * Parses a JSON object correponding to the serialize function.
  42665. */
  42666. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42667. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42668. };
  42669. __decorate([
  42670. BABYLON.serializeAsColor3(),
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42672. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42673. __decorate([
  42674. BABYLON.serializeAsTexture(),
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42676. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42677. __decorate([
  42678. BABYLON.serialize(),
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42681. __decorate([
  42682. BABYLON.serialize(),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42684. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42685. __decorate([
  42686. BABYLON.serializeAsTexture(),
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42688. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42689. return PBRMetallicRoughnessMaterial;
  42690. }(BABYLON.PBRBaseSimpleMaterial));
  42691. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42692. })(BABYLON || (BABYLON = {}));
  42693. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42694. var BABYLON;
  42695. (function (BABYLON) {
  42696. /**
  42697. * The PBR material of BJS following the specular glossiness convention.
  42698. *
  42699. * This fits to the PBR convention in the GLTF definition:
  42700. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42701. */
  42702. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42703. __extends(PBRSpecularGlossinessMaterial, _super);
  42704. /**
  42705. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42706. *
  42707. * @param name The material name
  42708. * @param scene The scene the material will be use in.
  42709. */
  42710. function PBRSpecularGlossinessMaterial(name, scene) {
  42711. var _this = _super.call(this, name, scene) || this;
  42712. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42713. return _this;
  42714. }
  42715. /**
  42716. * Return the currrent class name of the material.
  42717. */
  42718. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42719. return "PBRSpecularGlossinessMaterial";
  42720. };
  42721. /**
  42722. * Return the active textures of the material.
  42723. */
  42724. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42725. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42726. if (this.diffuseTexture) {
  42727. activeTextures.push(this.diffuseTexture);
  42728. }
  42729. if (this.specularGlossinessTexture) {
  42730. activeTextures.push(this.specularGlossinessTexture);
  42731. }
  42732. return activeTextures;
  42733. };
  42734. /**
  42735. * Checks to see if a texture is used in the material.
  42736. * @param texture - Base texture to use.
  42737. * @returns - Boolean specifying if a texture is used in the material.
  42738. */
  42739. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42740. if (_super.prototype.hasTexture.call(this, texture)) {
  42741. return true;
  42742. }
  42743. if (this.diffuseTexture === texture) {
  42744. return true;
  42745. }
  42746. if (this.specularGlossinessTexture === texture) {
  42747. return true;
  42748. }
  42749. return false;
  42750. };
  42751. /**
  42752. * Makes a duplicate of the current material.
  42753. * @param name - name to use for the new material.
  42754. */
  42755. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42756. var _this = this;
  42757. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42758. clone.id = name;
  42759. clone.name = name;
  42760. return clone;
  42761. };
  42762. /**
  42763. * Serialize the material to a parsable JSON object.
  42764. */
  42765. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42767. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42768. return serializationObject;
  42769. };
  42770. /**
  42771. * Parses a JSON object correponding to the serialize function.
  42772. */
  42773. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42774. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42775. };
  42776. __decorate([
  42777. BABYLON.serializeAsColor3("diffuse"),
  42778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42779. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42780. __decorate([
  42781. BABYLON.serializeAsTexture(),
  42782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42783. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42784. __decorate([
  42785. BABYLON.serializeAsColor3("specular"),
  42786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42787. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42788. __decorate([
  42789. BABYLON.serialize(),
  42790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42791. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42792. __decorate([
  42793. BABYLON.serializeAsTexture(),
  42794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42795. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42796. return PBRSpecularGlossinessMaterial;
  42797. }(BABYLON.PBRBaseSimpleMaterial));
  42798. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42799. })(BABYLON || (BABYLON = {}));
  42800. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42801. var BABYLON;
  42802. (function (BABYLON) {
  42803. BABYLON.CameraInputTypes = {};
  42804. var CameraInputsManager = /** @class */ (function () {
  42805. function CameraInputsManager(camera) {
  42806. this.attached = {};
  42807. this.camera = camera;
  42808. this.checkInputs = function () { };
  42809. }
  42810. /**
  42811. * Add an input method to a camera.
  42812. * builtin inputs example: camera.inputs.addGamepad();
  42813. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42814. * @param input camera input method
  42815. */
  42816. CameraInputsManager.prototype.add = function (input) {
  42817. var type = input.getSimpleName();
  42818. if (this.attached[type]) {
  42819. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42820. return;
  42821. }
  42822. this.attached[type] = input;
  42823. input.camera = this.camera;
  42824. //for checkInputs, we are dynamically creating a function
  42825. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42826. if (input.checkInputs) {
  42827. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42828. }
  42829. if (this.attachedElement) {
  42830. input.attachControl(this.attachedElement);
  42831. }
  42832. };
  42833. /**
  42834. * Remove a specific input method from a camera
  42835. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42836. * @param inputToRemove camera input method
  42837. */
  42838. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42839. for (var cam in this.attached) {
  42840. var input = this.attached[cam];
  42841. if (input === inputToRemove) {
  42842. input.detachControl(this.attachedElement);
  42843. input.camera = null;
  42844. delete this.attached[cam];
  42845. this.rebuildInputCheck();
  42846. }
  42847. }
  42848. };
  42849. CameraInputsManager.prototype.removeByType = function (inputType) {
  42850. for (var cam in this.attached) {
  42851. var input = this.attached[cam];
  42852. if (input.getClassName() === inputType) {
  42853. input.detachControl(this.attachedElement);
  42854. input.camera = null;
  42855. delete this.attached[cam];
  42856. this.rebuildInputCheck();
  42857. }
  42858. }
  42859. };
  42860. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42861. var current = this.checkInputs;
  42862. return function () {
  42863. current();
  42864. fn();
  42865. };
  42866. };
  42867. CameraInputsManager.prototype.attachInput = function (input) {
  42868. if (this.attachedElement) {
  42869. input.attachControl(this.attachedElement, this.noPreventDefault);
  42870. }
  42871. };
  42872. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42873. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42874. if (this.attachedElement) {
  42875. return;
  42876. }
  42877. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42878. this.attachedElement = element;
  42879. this.noPreventDefault = noPreventDefault;
  42880. for (var cam in this.attached) {
  42881. this.attached[cam].attachControl(element, noPreventDefault);
  42882. }
  42883. };
  42884. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42885. if (disconnect === void 0) { disconnect = false; }
  42886. if (this.attachedElement !== element) {
  42887. return;
  42888. }
  42889. for (var cam in this.attached) {
  42890. this.attached[cam].detachControl(element);
  42891. if (disconnect) {
  42892. this.attached[cam].camera = null;
  42893. }
  42894. }
  42895. this.attachedElement = null;
  42896. };
  42897. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42898. this.checkInputs = function () { };
  42899. for (var cam in this.attached) {
  42900. var input = this.attached[cam];
  42901. if (input.checkInputs) {
  42902. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42903. }
  42904. }
  42905. };
  42906. /**
  42907. * Remove all attached input methods from a camera
  42908. */
  42909. CameraInputsManager.prototype.clear = function () {
  42910. if (this.attachedElement) {
  42911. this.detachElement(this.attachedElement, true);
  42912. }
  42913. this.attached = {};
  42914. this.attachedElement = null;
  42915. this.checkInputs = function () { };
  42916. };
  42917. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42918. var inputs = {};
  42919. for (var cam in this.attached) {
  42920. var input = this.attached[cam];
  42921. var res = BABYLON.SerializationHelper.Serialize(input);
  42922. inputs[input.getClassName()] = res;
  42923. }
  42924. serializedCamera.inputsmgr = inputs;
  42925. };
  42926. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42927. var parsedInputs = parsedCamera.inputsmgr;
  42928. if (parsedInputs) {
  42929. this.clear();
  42930. for (var n in parsedInputs) {
  42931. var construct = BABYLON.CameraInputTypes[n];
  42932. if (construct) {
  42933. var parsedinput = parsedInputs[n];
  42934. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42935. this.add(input);
  42936. }
  42937. }
  42938. }
  42939. else {
  42940. //2016-03-08 this part is for managing backward compatibility
  42941. for (var n in this.attached) {
  42942. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42943. if (construct) {
  42944. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42945. this.remove(this.attached[n]);
  42946. this.add(input);
  42947. }
  42948. }
  42949. }
  42950. };
  42951. return CameraInputsManager;
  42952. }());
  42953. BABYLON.CameraInputsManager = CameraInputsManager;
  42954. })(BABYLON || (BABYLON = {}));
  42955. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42956. var BABYLON;
  42957. (function (BABYLON) {
  42958. var TargetCamera = /** @class */ (function (_super) {
  42959. __extends(TargetCamera, _super);
  42960. function TargetCamera(name, position, scene) {
  42961. var _this = _super.call(this, name, position, scene) || this;
  42962. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42963. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42964. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42965. _this.speed = 2.0;
  42966. _this.noRotationConstraint = false;
  42967. _this.lockedTarget = null;
  42968. _this._currentTarget = BABYLON.Vector3.Zero();
  42969. _this._viewMatrix = BABYLON.Matrix.Zero();
  42970. _this._camMatrix = BABYLON.Matrix.Zero();
  42971. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42972. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42973. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42974. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42975. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42976. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42977. _this._tempMatrix = BABYLON.Matrix.Zero();
  42978. return _this;
  42979. }
  42980. TargetCamera.prototype.getFrontPosition = function (distance) {
  42981. this.getWorldMatrix();
  42982. var direction = this.getTarget().subtract(this.position);
  42983. direction.normalize();
  42984. direction.scaleInPlace(distance);
  42985. return this.globalPosition.add(direction);
  42986. };
  42987. TargetCamera.prototype._getLockedTargetPosition = function () {
  42988. if (!this.lockedTarget) {
  42989. return null;
  42990. }
  42991. if (this.lockedTarget.absolutePosition) {
  42992. this.lockedTarget.computeWorldMatrix();
  42993. }
  42994. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42995. };
  42996. TargetCamera.prototype.storeState = function () {
  42997. this._storedPosition = this.position.clone();
  42998. this._storedRotation = this.rotation.clone();
  42999. if (this.rotationQuaternion) {
  43000. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43001. }
  43002. return _super.prototype.storeState.call(this);
  43003. };
  43004. /**
  43005. * Restored camera state. You must call storeState() first
  43006. */
  43007. TargetCamera.prototype._restoreStateValues = function () {
  43008. if (!_super.prototype._restoreStateValues.call(this)) {
  43009. return false;
  43010. }
  43011. this.position = this._storedPosition.clone();
  43012. this.rotation = this._storedRotation.clone();
  43013. if (this.rotationQuaternion) {
  43014. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43015. }
  43016. this.cameraDirection.copyFromFloats(0, 0, 0);
  43017. this.cameraRotation.copyFromFloats(0, 0);
  43018. return true;
  43019. };
  43020. // Cache
  43021. TargetCamera.prototype._initCache = function () {
  43022. _super.prototype._initCache.call(this);
  43023. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43024. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43025. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43026. };
  43027. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43028. if (!ignoreParentClass) {
  43029. _super.prototype._updateCache.call(this);
  43030. }
  43031. var lockedTargetPosition = this._getLockedTargetPosition();
  43032. if (!lockedTargetPosition) {
  43033. this._cache.lockedTarget = null;
  43034. }
  43035. else {
  43036. if (!this._cache.lockedTarget) {
  43037. this._cache.lockedTarget = lockedTargetPosition.clone();
  43038. }
  43039. else {
  43040. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43041. }
  43042. }
  43043. this._cache.rotation.copyFrom(this.rotation);
  43044. if (this.rotationQuaternion)
  43045. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43046. };
  43047. // Synchronized
  43048. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43049. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43050. return false;
  43051. }
  43052. var lockedTargetPosition = this._getLockedTargetPosition();
  43053. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43054. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43055. };
  43056. // Methods
  43057. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43058. var engine = this.getEngine();
  43059. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43060. };
  43061. // Target
  43062. TargetCamera.prototype.setTarget = function (target) {
  43063. this.upVector.normalize();
  43064. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43065. this._camMatrix.invert();
  43066. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43067. var vDir = target.subtract(this.position);
  43068. if (vDir.x >= 0.0) {
  43069. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43070. }
  43071. else {
  43072. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43073. }
  43074. this.rotation.z = 0;
  43075. if (isNaN(this.rotation.x)) {
  43076. this.rotation.x = 0;
  43077. }
  43078. if (isNaN(this.rotation.y)) {
  43079. this.rotation.y = 0;
  43080. }
  43081. if (isNaN(this.rotation.z)) {
  43082. this.rotation.z = 0;
  43083. }
  43084. if (this.rotationQuaternion) {
  43085. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43086. }
  43087. };
  43088. /**
  43089. * Return the current target position of the camera. This value is expressed in local space.
  43090. */
  43091. TargetCamera.prototype.getTarget = function () {
  43092. return this._currentTarget;
  43093. };
  43094. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43095. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43096. };
  43097. TargetCamera.prototype._updatePosition = function () {
  43098. if (this.parent) {
  43099. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43100. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43101. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43102. return;
  43103. }
  43104. this.position.addInPlace(this.cameraDirection);
  43105. };
  43106. TargetCamera.prototype._checkInputs = function () {
  43107. var needToMove = this._decideIfNeedsToMove();
  43108. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43109. // Move
  43110. if (needToMove) {
  43111. this._updatePosition();
  43112. }
  43113. // Rotate
  43114. if (needToRotate) {
  43115. this.rotation.x += this.cameraRotation.x;
  43116. this.rotation.y += this.cameraRotation.y;
  43117. //rotate, if quaternion is set and rotation was used
  43118. if (this.rotationQuaternion) {
  43119. var len = this.rotation.lengthSquared();
  43120. if (len) {
  43121. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43122. }
  43123. }
  43124. if (!this.noRotationConstraint) {
  43125. var limit = (Math.PI / 2) * 0.95;
  43126. if (this.rotation.x > limit)
  43127. this.rotation.x = limit;
  43128. if (this.rotation.x < -limit)
  43129. this.rotation.x = -limit;
  43130. }
  43131. }
  43132. // Inertia
  43133. if (needToMove) {
  43134. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43135. this.cameraDirection.x = 0;
  43136. }
  43137. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43138. this.cameraDirection.y = 0;
  43139. }
  43140. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43141. this.cameraDirection.z = 0;
  43142. }
  43143. this.cameraDirection.scaleInPlace(this.inertia);
  43144. }
  43145. if (needToRotate) {
  43146. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43147. this.cameraRotation.x = 0;
  43148. }
  43149. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43150. this.cameraRotation.y = 0;
  43151. }
  43152. this.cameraRotation.scaleInPlace(this.inertia);
  43153. }
  43154. _super.prototype._checkInputs.call(this);
  43155. };
  43156. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43157. if (this.rotationQuaternion) {
  43158. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43159. }
  43160. else {
  43161. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43162. }
  43163. //update the up vector!
  43164. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43165. };
  43166. TargetCamera.prototype._getViewMatrix = function () {
  43167. if (this.lockedTarget) {
  43168. this.setTarget(this._getLockedTargetPosition());
  43169. }
  43170. // Compute
  43171. this._updateCameraRotationMatrix();
  43172. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43173. // Computing target and final matrix
  43174. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43175. if (this.getScene().useRightHandedSystem) {
  43176. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43177. }
  43178. else {
  43179. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43180. }
  43181. return this._viewMatrix;
  43182. };
  43183. /**
  43184. * @override
  43185. * Override Camera.createRigCamera
  43186. */
  43187. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43188. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43189. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43190. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43191. if (!this.rotationQuaternion) {
  43192. this.rotationQuaternion = new BABYLON.Quaternion();
  43193. }
  43194. rigCamera._cameraRigParams = {};
  43195. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43196. }
  43197. return rigCamera;
  43198. }
  43199. return null;
  43200. };
  43201. /**
  43202. * @override
  43203. * Override Camera._updateRigCameras
  43204. */
  43205. TargetCamera.prototype._updateRigCameras = function () {
  43206. var camLeft = this._rigCameras[0];
  43207. var camRight = this._rigCameras[1];
  43208. switch (this.cameraRigMode) {
  43209. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43210. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43211. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43213. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43214. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43215. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43216. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43217. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43218. camLeft.setTarget(this.getTarget());
  43219. camRight.setTarget(this.getTarget());
  43220. break;
  43221. case BABYLON.Camera.RIG_MODE_VR:
  43222. if (camLeft.rotationQuaternion) {
  43223. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43224. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43225. }
  43226. else {
  43227. camLeft.rotation.copyFrom(this.rotation);
  43228. camRight.rotation.copyFrom(this.rotation);
  43229. }
  43230. camLeft.position.copyFrom(this.position);
  43231. camRight.position.copyFrom(this.position);
  43232. break;
  43233. }
  43234. _super.prototype._updateRigCameras.call(this);
  43235. };
  43236. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43237. if (!this._rigCamTransformMatrix) {
  43238. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43239. }
  43240. var target = this.getTarget();
  43241. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43242. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43243. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43244. };
  43245. TargetCamera.prototype.getClassName = function () {
  43246. return "TargetCamera";
  43247. };
  43248. __decorate([
  43249. BABYLON.serializeAsVector3()
  43250. ], TargetCamera.prototype, "rotation", void 0);
  43251. __decorate([
  43252. BABYLON.serialize()
  43253. ], TargetCamera.prototype, "speed", void 0);
  43254. __decorate([
  43255. BABYLON.serializeAsMeshReference("lockedTargetId")
  43256. ], TargetCamera.prototype, "lockedTarget", void 0);
  43257. return TargetCamera;
  43258. }(BABYLON.Camera));
  43259. BABYLON.TargetCamera = TargetCamera;
  43260. })(BABYLON || (BABYLON = {}));
  43261. //# sourceMappingURL=babylon.targetCamera.js.map
  43262. var BABYLON;
  43263. (function (BABYLON) {
  43264. var FreeCameraMouseInput = /** @class */ (function () {
  43265. function FreeCameraMouseInput(touchEnabled) {
  43266. if (touchEnabled === void 0) { touchEnabled = true; }
  43267. this.touchEnabled = touchEnabled;
  43268. this.buttons = [0, 1, 2];
  43269. this.angularSensibility = 2000.0;
  43270. this.previousPosition = null;
  43271. }
  43272. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43273. var _this = this;
  43274. var engine = this.camera.getEngine();
  43275. if (!this._pointerInput) {
  43276. this._pointerInput = function (p, s) {
  43277. var evt = p.event;
  43278. if (engine.isInVRExclusivePointerMode) {
  43279. return;
  43280. }
  43281. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43282. return;
  43283. }
  43284. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43285. return;
  43286. }
  43287. var srcElement = (evt.srcElement || evt.target);
  43288. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43289. try {
  43290. srcElement.setPointerCapture(evt.pointerId);
  43291. }
  43292. catch (e) {
  43293. //Nothing to do with the error. Execution will continue.
  43294. }
  43295. _this.previousPosition = {
  43296. x: evt.clientX,
  43297. y: evt.clientY
  43298. };
  43299. if (!noPreventDefault) {
  43300. evt.preventDefault();
  43301. element.focus();
  43302. }
  43303. }
  43304. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43305. try {
  43306. srcElement.releasePointerCapture(evt.pointerId);
  43307. }
  43308. catch (e) {
  43309. //Nothing to do with the error.
  43310. }
  43311. _this.previousPosition = null;
  43312. if (!noPreventDefault) {
  43313. evt.preventDefault();
  43314. }
  43315. }
  43316. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43317. if (!_this.previousPosition || engine.isPointerLock) {
  43318. return;
  43319. }
  43320. var offsetX = evt.clientX - _this.previousPosition.x;
  43321. var offsetY = evt.clientY - _this.previousPosition.y;
  43322. if (_this.camera.getScene().useRightHandedSystem) {
  43323. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43324. }
  43325. else {
  43326. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43327. }
  43328. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43329. _this.previousPosition = {
  43330. x: evt.clientX,
  43331. y: evt.clientY
  43332. };
  43333. if (!noPreventDefault) {
  43334. evt.preventDefault();
  43335. }
  43336. }
  43337. };
  43338. }
  43339. this._onMouseMove = function (evt) {
  43340. if (!engine.isPointerLock) {
  43341. return;
  43342. }
  43343. if (engine.isInVRExclusivePointerMode) {
  43344. return;
  43345. }
  43346. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43347. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43348. if (_this.camera.getScene().useRightHandedSystem) {
  43349. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43350. }
  43351. else {
  43352. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43353. }
  43354. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43355. _this.previousPosition = null;
  43356. if (!noPreventDefault) {
  43357. evt.preventDefault();
  43358. }
  43359. };
  43360. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43361. element.addEventListener("mousemove", this._onMouseMove, false);
  43362. };
  43363. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43364. if (this._observer && element) {
  43365. this.camera.getScene().onPointerObservable.remove(this._observer);
  43366. if (this._onMouseMove) {
  43367. element.removeEventListener("mousemove", this._onMouseMove);
  43368. }
  43369. this._observer = null;
  43370. this._onMouseMove = null;
  43371. this.previousPosition = null;
  43372. }
  43373. };
  43374. FreeCameraMouseInput.prototype.getClassName = function () {
  43375. return "FreeCameraMouseInput";
  43376. };
  43377. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43378. return "mouse";
  43379. };
  43380. __decorate([
  43381. BABYLON.serialize()
  43382. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43383. __decorate([
  43384. BABYLON.serialize()
  43385. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43386. return FreeCameraMouseInput;
  43387. }());
  43388. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43389. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43390. })(BABYLON || (BABYLON = {}));
  43391. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43392. var BABYLON;
  43393. (function (BABYLON) {
  43394. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43395. function FreeCameraKeyboardMoveInput() {
  43396. this._keys = new Array();
  43397. this.keysUp = [38];
  43398. this.keysDown = [40];
  43399. this.keysLeft = [37];
  43400. this.keysRight = [39];
  43401. }
  43402. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43403. var _this = this;
  43404. if (this._onCanvasBlurObserver) {
  43405. return;
  43406. }
  43407. this._scene = this.camera.getScene();
  43408. this._engine = this._scene.getEngine();
  43409. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43410. _this._keys = [];
  43411. });
  43412. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43413. var evt = info.event;
  43414. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43415. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43416. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43417. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43418. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43419. var index = _this._keys.indexOf(evt.keyCode);
  43420. if (index === -1) {
  43421. _this._keys.push(evt.keyCode);
  43422. }
  43423. if (!noPreventDefault) {
  43424. evt.preventDefault();
  43425. }
  43426. }
  43427. }
  43428. else {
  43429. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43430. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43431. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43432. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43433. var index = _this._keys.indexOf(evt.keyCode);
  43434. if (index >= 0) {
  43435. _this._keys.splice(index, 1);
  43436. }
  43437. if (!noPreventDefault) {
  43438. evt.preventDefault();
  43439. }
  43440. }
  43441. }
  43442. });
  43443. };
  43444. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43445. if (this._scene) {
  43446. if (this._onKeyboardObserver) {
  43447. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43448. }
  43449. if (this._onCanvasBlurObserver) {
  43450. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43451. }
  43452. this._onKeyboardObserver = null;
  43453. this._onCanvasBlurObserver = null;
  43454. }
  43455. this._keys = [];
  43456. };
  43457. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43458. if (this._onKeyboardObserver) {
  43459. var camera = this.camera;
  43460. // Keyboard
  43461. for (var index = 0; index < this._keys.length; index++) {
  43462. var keyCode = this._keys[index];
  43463. var speed = camera._computeLocalCameraSpeed();
  43464. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43465. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43466. }
  43467. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43468. camera._localDirection.copyFromFloats(0, 0, speed);
  43469. }
  43470. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43471. camera._localDirection.copyFromFloats(speed, 0, 0);
  43472. }
  43473. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43474. camera._localDirection.copyFromFloats(0, 0, -speed);
  43475. }
  43476. if (camera.getScene().useRightHandedSystem) {
  43477. camera._localDirection.z *= -1;
  43478. }
  43479. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43480. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43481. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43482. }
  43483. }
  43484. };
  43485. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43486. return "FreeCameraKeyboardMoveInput";
  43487. };
  43488. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43489. this._keys = [];
  43490. };
  43491. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43492. return "keyboard";
  43493. };
  43494. __decorate([
  43495. BABYLON.serialize()
  43496. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43497. __decorate([
  43498. BABYLON.serialize()
  43499. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43500. __decorate([
  43501. BABYLON.serialize()
  43502. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43503. __decorate([
  43504. BABYLON.serialize()
  43505. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43506. return FreeCameraKeyboardMoveInput;
  43507. }());
  43508. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43509. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43510. })(BABYLON || (BABYLON = {}));
  43511. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43512. var BABYLON;
  43513. (function (BABYLON) {
  43514. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43515. __extends(FreeCameraInputsManager, _super);
  43516. function FreeCameraInputsManager(camera) {
  43517. return _super.call(this, camera) || this;
  43518. }
  43519. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43520. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43521. return this;
  43522. };
  43523. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43524. if (touchEnabled === void 0) { touchEnabled = true; }
  43525. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43526. return this;
  43527. };
  43528. FreeCameraInputsManager.prototype.addGamepad = function () {
  43529. this.add(new BABYLON.FreeCameraGamepadInput());
  43530. return this;
  43531. };
  43532. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43533. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43534. return this;
  43535. };
  43536. FreeCameraInputsManager.prototype.addTouch = function () {
  43537. this.add(new BABYLON.FreeCameraTouchInput());
  43538. return this;
  43539. };
  43540. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43541. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43542. return this;
  43543. };
  43544. return FreeCameraInputsManager;
  43545. }(BABYLON.CameraInputsManager));
  43546. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43547. })(BABYLON || (BABYLON = {}));
  43548. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43549. var BABYLON;
  43550. (function (BABYLON) {
  43551. var FreeCamera = /** @class */ (function (_super) {
  43552. __extends(FreeCamera, _super);
  43553. function FreeCamera(name, position, scene) {
  43554. var _this = _super.call(this, name, position, scene) || this;
  43555. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43556. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43557. _this.checkCollisions = false;
  43558. _this.applyGravity = false;
  43559. _this._needMoveForGravity = false;
  43560. _this._oldPosition = BABYLON.Vector3.Zero();
  43561. _this._diffPosition = BABYLON.Vector3.Zero();
  43562. _this._newPosition = BABYLON.Vector3.Zero();
  43563. // Collisions
  43564. _this._collisionMask = -1;
  43565. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43566. if (collidedMesh === void 0) { collidedMesh = null; }
  43567. //TODO move this to the collision coordinator!
  43568. if (_this.getScene().workerCollisions)
  43569. newPosition.multiplyInPlace(_this._collider._radius);
  43570. var updatePosition = function (newPos) {
  43571. _this._newPosition.copyFrom(newPos);
  43572. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43573. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43574. _this.position.addInPlace(_this._diffPosition);
  43575. if (_this.onCollide && collidedMesh) {
  43576. _this.onCollide(collidedMesh);
  43577. }
  43578. }
  43579. };
  43580. updatePosition(newPosition);
  43581. };
  43582. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43583. _this.inputs.addKeyboard().addMouse();
  43584. return _this;
  43585. }
  43586. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43587. //-- begin properties for backward compatibility for inputs
  43588. /**
  43589. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43590. * Higher values reduce sensitivity.
  43591. */
  43592. get: function () {
  43593. var mouse = this.inputs.attached["mouse"];
  43594. if (mouse)
  43595. return mouse.angularSensibility;
  43596. return 0;
  43597. },
  43598. /**
  43599. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43600. * Higher values reduce sensitivity.
  43601. */
  43602. set: function (value) {
  43603. var mouse = this.inputs.attached["mouse"];
  43604. if (mouse)
  43605. mouse.angularSensibility = value;
  43606. },
  43607. enumerable: true,
  43608. configurable: true
  43609. });
  43610. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43611. get: function () {
  43612. var keyboard = this.inputs.attached["keyboard"];
  43613. if (keyboard)
  43614. return keyboard.keysUp;
  43615. return [];
  43616. },
  43617. set: function (value) {
  43618. var keyboard = this.inputs.attached["keyboard"];
  43619. if (keyboard)
  43620. keyboard.keysUp = value;
  43621. },
  43622. enumerable: true,
  43623. configurable: true
  43624. });
  43625. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43626. get: function () {
  43627. var keyboard = this.inputs.attached["keyboard"];
  43628. if (keyboard)
  43629. return keyboard.keysDown;
  43630. return [];
  43631. },
  43632. set: function (value) {
  43633. var keyboard = this.inputs.attached["keyboard"];
  43634. if (keyboard)
  43635. keyboard.keysDown = value;
  43636. },
  43637. enumerable: true,
  43638. configurable: true
  43639. });
  43640. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43641. get: function () {
  43642. var keyboard = this.inputs.attached["keyboard"];
  43643. if (keyboard)
  43644. return keyboard.keysLeft;
  43645. return [];
  43646. },
  43647. set: function (value) {
  43648. var keyboard = this.inputs.attached["keyboard"];
  43649. if (keyboard)
  43650. keyboard.keysLeft = value;
  43651. },
  43652. enumerable: true,
  43653. configurable: true
  43654. });
  43655. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43656. get: function () {
  43657. var keyboard = this.inputs.attached["keyboard"];
  43658. if (keyboard)
  43659. return keyboard.keysRight;
  43660. return [];
  43661. },
  43662. set: function (value) {
  43663. var keyboard = this.inputs.attached["keyboard"];
  43664. if (keyboard)
  43665. keyboard.keysRight = value;
  43666. },
  43667. enumerable: true,
  43668. configurable: true
  43669. });
  43670. // Controls
  43671. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43672. this.inputs.attachElement(element, noPreventDefault);
  43673. };
  43674. FreeCamera.prototype.detachControl = function (element) {
  43675. this.inputs.detachElement(element);
  43676. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43677. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43678. };
  43679. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43680. get: function () {
  43681. return this._collisionMask;
  43682. },
  43683. set: function (mask) {
  43684. this._collisionMask = !isNaN(mask) ? mask : -1;
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43690. var globalPosition;
  43691. if (this.parent) {
  43692. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43693. }
  43694. else {
  43695. globalPosition = this.position;
  43696. }
  43697. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43698. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43699. if (!this._collider) {
  43700. this._collider = new BABYLON.Collider();
  43701. }
  43702. this._collider._radius = this.ellipsoid;
  43703. this._collider.collisionMask = this._collisionMask;
  43704. //no need for clone, as long as gravity is not on.
  43705. var actualDisplacement = displacement;
  43706. //add gravity to the direction to prevent the dual-collision checking
  43707. if (this.applyGravity) {
  43708. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43709. actualDisplacement = displacement.add(this.getScene().gravity);
  43710. }
  43711. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43712. };
  43713. FreeCamera.prototype._checkInputs = function () {
  43714. if (!this._localDirection) {
  43715. this._localDirection = BABYLON.Vector3.Zero();
  43716. this._transformedDirection = BABYLON.Vector3.Zero();
  43717. }
  43718. this.inputs.checkInputs();
  43719. _super.prototype._checkInputs.call(this);
  43720. };
  43721. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43722. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43723. };
  43724. FreeCamera.prototype._updatePosition = function () {
  43725. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43726. this._collideWithWorld(this.cameraDirection);
  43727. }
  43728. else {
  43729. _super.prototype._updatePosition.call(this);
  43730. }
  43731. };
  43732. FreeCamera.prototype.dispose = function () {
  43733. this.inputs.clear();
  43734. _super.prototype.dispose.call(this);
  43735. };
  43736. FreeCamera.prototype.getClassName = function () {
  43737. return "FreeCamera";
  43738. };
  43739. __decorate([
  43740. BABYLON.serializeAsVector3()
  43741. ], FreeCamera.prototype, "ellipsoid", void 0);
  43742. __decorate([
  43743. BABYLON.serializeAsVector3()
  43744. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43745. __decorate([
  43746. BABYLON.serialize()
  43747. ], FreeCamera.prototype, "checkCollisions", void 0);
  43748. __decorate([
  43749. BABYLON.serialize()
  43750. ], FreeCamera.prototype, "applyGravity", void 0);
  43751. return FreeCamera;
  43752. }(BABYLON.TargetCamera));
  43753. BABYLON.FreeCamera = FreeCamera;
  43754. })(BABYLON || (BABYLON = {}));
  43755. //# sourceMappingURL=babylon.freeCamera.js.map
  43756. var BABYLON;
  43757. (function (BABYLON) {
  43758. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43759. function ArcRotateCameraKeyboardMoveInput() {
  43760. this._keys = new Array();
  43761. this.keysUp = [38];
  43762. this.keysDown = [40];
  43763. this.keysLeft = [37];
  43764. this.keysRight = [39];
  43765. this.keysReset = [220];
  43766. this.panningSensibility = 50.0;
  43767. this.zoomingSensibility = 25.0;
  43768. this.useAltToZoom = true;
  43769. }
  43770. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43771. var _this = this;
  43772. if (this._onCanvasBlurObserver) {
  43773. return;
  43774. }
  43775. this._scene = this.camera.getScene();
  43776. this._engine = this._scene.getEngine();
  43777. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43778. _this._keys = [];
  43779. });
  43780. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43781. var evt = info.event;
  43782. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43783. _this._ctrlPressed = evt.ctrlKey;
  43784. _this._altPressed = evt.altKey;
  43785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43788. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43789. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43790. var index = _this._keys.indexOf(evt.keyCode);
  43791. if (index === -1) {
  43792. _this._keys.push(evt.keyCode);
  43793. }
  43794. if (evt.preventDefault) {
  43795. if (!noPreventDefault) {
  43796. evt.preventDefault();
  43797. }
  43798. }
  43799. }
  43800. }
  43801. else {
  43802. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43803. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43804. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43805. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43806. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43807. var index = _this._keys.indexOf(evt.keyCode);
  43808. if (index >= 0) {
  43809. _this._keys.splice(index, 1);
  43810. }
  43811. if (evt.preventDefault) {
  43812. if (!noPreventDefault) {
  43813. evt.preventDefault();
  43814. }
  43815. }
  43816. }
  43817. }
  43818. });
  43819. };
  43820. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43821. if (this._scene) {
  43822. if (this._onKeyboardObserver) {
  43823. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43824. }
  43825. if (this._onCanvasBlurObserver) {
  43826. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43827. }
  43828. this._onKeyboardObserver = null;
  43829. this._onCanvasBlurObserver = null;
  43830. }
  43831. this._keys = [];
  43832. };
  43833. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43834. if (this._onKeyboardObserver) {
  43835. var camera = this.camera;
  43836. for (var index = 0; index < this._keys.length; index++) {
  43837. var keyCode = this._keys[index];
  43838. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43839. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43840. camera.inertialPanningX -= 1 / this.panningSensibility;
  43841. }
  43842. else {
  43843. camera.inertialAlphaOffset -= 0.01;
  43844. }
  43845. }
  43846. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43847. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43848. camera.inertialPanningY += 1 / this.panningSensibility;
  43849. }
  43850. else if (this._altPressed && this.useAltToZoom) {
  43851. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43852. }
  43853. else {
  43854. camera.inertialBetaOffset -= 0.01;
  43855. }
  43856. }
  43857. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43858. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43859. camera.inertialPanningX += 1 / this.panningSensibility;
  43860. }
  43861. else {
  43862. camera.inertialAlphaOffset += 0.01;
  43863. }
  43864. }
  43865. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43866. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43867. camera.inertialPanningY -= 1 / this.panningSensibility;
  43868. }
  43869. else if (this._altPressed && this.useAltToZoom) {
  43870. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43871. }
  43872. else {
  43873. camera.inertialBetaOffset += 0.01;
  43874. }
  43875. }
  43876. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43877. camera.restoreState();
  43878. }
  43879. }
  43880. }
  43881. };
  43882. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43883. return "ArcRotateCameraKeyboardMoveInput";
  43884. };
  43885. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43886. return "keyboard";
  43887. };
  43888. __decorate([
  43889. BABYLON.serialize()
  43890. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43891. __decorate([
  43892. BABYLON.serialize()
  43893. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43894. __decorate([
  43895. BABYLON.serialize()
  43896. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43897. __decorate([
  43898. BABYLON.serialize()
  43899. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43900. __decorate([
  43901. BABYLON.serialize()
  43902. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43903. __decorate([
  43904. BABYLON.serialize()
  43905. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43906. __decorate([
  43907. BABYLON.serialize()
  43908. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43909. __decorate([
  43910. BABYLON.serialize()
  43911. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43912. return ArcRotateCameraKeyboardMoveInput;
  43913. }());
  43914. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43915. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43916. })(BABYLON || (BABYLON = {}));
  43917. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43918. var BABYLON;
  43919. (function (BABYLON) {
  43920. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43921. function ArcRotateCameraMouseWheelInput() {
  43922. this.wheelPrecision = 3.0;
  43923. /**
  43924. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43925. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43926. */
  43927. this.wheelDeltaPercentage = 0;
  43928. }
  43929. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43930. var _this = this;
  43931. this._wheel = function (p, s) {
  43932. //sanity check - this should be a PointerWheel event.
  43933. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43934. return;
  43935. var event = p.event;
  43936. var delta = 0;
  43937. if (event.wheelDelta) {
  43938. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43939. }
  43940. else if (event.detail) {
  43941. delta = -event.detail / _this.wheelPrecision;
  43942. }
  43943. if (delta)
  43944. _this.camera.inertialRadiusOffset += delta;
  43945. if (event.preventDefault) {
  43946. if (!noPreventDefault) {
  43947. event.preventDefault();
  43948. }
  43949. }
  43950. };
  43951. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43952. };
  43953. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43954. if (this._observer && element) {
  43955. this.camera.getScene().onPointerObservable.remove(this._observer);
  43956. this._observer = null;
  43957. this._wheel = null;
  43958. }
  43959. };
  43960. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43961. return "ArcRotateCameraMouseWheelInput";
  43962. };
  43963. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43964. return "mousewheel";
  43965. };
  43966. __decorate([
  43967. BABYLON.serialize()
  43968. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43969. __decorate([
  43970. BABYLON.serialize()
  43971. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43972. return ArcRotateCameraMouseWheelInput;
  43973. }());
  43974. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43975. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43976. })(BABYLON || (BABYLON = {}));
  43977. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43978. var BABYLON;
  43979. (function (BABYLON) {
  43980. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43981. function ArcRotateCameraPointersInput() {
  43982. this.buttons = [0, 1, 2];
  43983. this.angularSensibilityX = 1000.0;
  43984. this.angularSensibilityY = 1000.0;
  43985. this.pinchPrecision = 12.0;
  43986. /**
  43987. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43988. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43989. */
  43990. this.pinchDeltaPercentage = 0;
  43991. this.panningSensibility = 1000.0;
  43992. this.multiTouchPanning = true;
  43993. this.multiTouchPanAndZoom = true;
  43994. this._isPanClick = false;
  43995. this.pinchInwards = true;
  43996. }
  43997. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43998. var _this = this;
  43999. var engine = this.camera.getEngine();
  44000. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44001. var pointA = null;
  44002. var pointB = null;
  44003. var previousPinchSquaredDistance = 0;
  44004. var initialDistance = 0;
  44005. var twoFingerActivityCount = 0;
  44006. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44007. this._pointerInput = function (p, s) {
  44008. var evt = p.event;
  44009. var isTouch = p.event.pointerType === "touch";
  44010. if (engine.isInVRExclusivePointerMode) {
  44011. return;
  44012. }
  44013. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44014. return;
  44015. }
  44016. var srcElement = (evt.srcElement || evt.target);
  44017. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44018. try {
  44019. srcElement.setPointerCapture(evt.pointerId);
  44020. }
  44021. catch (e) {
  44022. //Nothing to do with the error. Execution will continue.
  44023. }
  44024. // Manage panning with pan button click
  44025. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44026. // manage pointers
  44027. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44028. if (pointA === null) {
  44029. pointA = cacheSoloPointer;
  44030. }
  44031. else if (pointB === null) {
  44032. pointB = cacheSoloPointer;
  44033. }
  44034. if (!noPreventDefault) {
  44035. evt.preventDefault();
  44036. element.focus();
  44037. }
  44038. }
  44039. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44040. _this.camera.restoreState();
  44041. }
  44042. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44043. try {
  44044. srcElement.releasePointerCapture(evt.pointerId);
  44045. }
  44046. catch (e) {
  44047. //Nothing to do with the error.
  44048. }
  44049. cacheSoloPointer = null;
  44050. previousPinchSquaredDistance = 0;
  44051. previousMultiTouchPanPosition.isPaning = false;
  44052. previousMultiTouchPanPosition.isPinching = false;
  44053. twoFingerActivityCount = 0;
  44054. initialDistance = 0;
  44055. if (!isTouch) {
  44056. pointB = null; // Mouse and pen are mono pointer
  44057. }
  44058. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44059. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44060. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44061. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44062. if (engine.badOS) {
  44063. pointA = pointB = null;
  44064. }
  44065. else {
  44066. //only remove the impacted pointer in case of multitouch allowing on most
  44067. //platforms switching from rotate to zoom and pan seamlessly.
  44068. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44069. pointA = pointB;
  44070. pointB = null;
  44071. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44072. }
  44073. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44074. pointB = null;
  44075. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44076. }
  44077. else {
  44078. pointA = pointB = null;
  44079. }
  44080. }
  44081. if (!noPreventDefault) {
  44082. evt.preventDefault();
  44083. }
  44084. }
  44085. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44086. if (!noPreventDefault) {
  44087. evt.preventDefault();
  44088. }
  44089. // One button down
  44090. if (pointA && pointB === null && cacheSoloPointer) {
  44091. if (_this.panningSensibility !== 0 &&
  44092. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44093. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44094. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44095. }
  44096. else {
  44097. var offsetX = evt.clientX - cacheSoloPointer.x;
  44098. var offsetY = evt.clientY - cacheSoloPointer.y;
  44099. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44100. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44101. }
  44102. cacheSoloPointer.x = evt.clientX;
  44103. cacheSoloPointer.y = evt.clientY;
  44104. }
  44105. else if (pointA && pointB) {
  44106. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44107. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44108. ed.x = evt.clientX;
  44109. ed.y = evt.clientY;
  44110. var direction = _this.pinchInwards ? 1 : -1;
  44111. var distX = pointA.x - pointB.x;
  44112. var distY = pointA.y - pointB.y;
  44113. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44114. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44115. if (previousPinchSquaredDistance === 0) {
  44116. initialDistance = pinchDistance;
  44117. previousPinchSquaredDistance = pinchSquaredDistance;
  44118. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44119. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44120. return;
  44121. }
  44122. if (_this.multiTouchPanAndZoom) {
  44123. if (_this.pinchDeltaPercentage) {
  44124. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44125. }
  44126. else {
  44127. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44128. (_this.pinchPrecision *
  44129. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44130. direction);
  44131. }
  44132. if (_this.panningSensibility !== 0) {
  44133. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44134. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44135. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44136. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44137. previousMultiTouchPanPosition.x = pointersCenterX;
  44138. previousMultiTouchPanPosition.y = pointersCenterY;
  44139. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44140. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44141. }
  44142. }
  44143. else {
  44144. twoFingerActivityCount++;
  44145. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44146. if (_this.pinchDeltaPercentage) {
  44147. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44148. }
  44149. else {
  44150. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44151. (_this.pinchPrecision *
  44152. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44153. direction);
  44154. }
  44155. previousMultiTouchPanPosition.isPaning = false;
  44156. previousMultiTouchPanPosition.isPinching = true;
  44157. }
  44158. else {
  44159. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44160. if (!previousMultiTouchPanPosition.isPaning) {
  44161. previousMultiTouchPanPosition.isPaning = true;
  44162. previousMultiTouchPanPosition.isPinching = false;
  44163. previousMultiTouchPanPosition.x = ed.x;
  44164. previousMultiTouchPanPosition.y = ed.y;
  44165. return;
  44166. }
  44167. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44168. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44169. }
  44170. }
  44171. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44172. previousMultiTouchPanPosition.x = ed.x;
  44173. previousMultiTouchPanPosition.y = ed.y;
  44174. }
  44175. }
  44176. previousPinchSquaredDistance = pinchSquaredDistance;
  44177. }
  44178. }
  44179. };
  44180. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44181. this._onContextMenu = function (evt) {
  44182. evt.preventDefault();
  44183. };
  44184. if (!this.camera._useCtrlForPanning) {
  44185. element.addEventListener("contextmenu", this._onContextMenu, false);
  44186. }
  44187. this._onLostFocus = function () {
  44188. //this._keys = [];
  44189. pointA = pointB = null;
  44190. previousPinchSquaredDistance = 0;
  44191. previousMultiTouchPanPosition.isPaning = false;
  44192. previousMultiTouchPanPosition.isPinching = false;
  44193. twoFingerActivityCount = 0;
  44194. cacheSoloPointer = null;
  44195. initialDistance = 0;
  44196. };
  44197. this._onMouseMove = function (evt) {
  44198. if (!engine.isPointerLock) {
  44199. return;
  44200. }
  44201. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44202. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44203. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44204. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44205. if (!noPreventDefault) {
  44206. evt.preventDefault();
  44207. }
  44208. };
  44209. this._onGestureStart = function (e) {
  44210. if (window.MSGesture === undefined) {
  44211. return;
  44212. }
  44213. if (!_this._MSGestureHandler) {
  44214. _this._MSGestureHandler = new MSGesture();
  44215. _this._MSGestureHandler.target = element;
  44216. }
  44217. _this._MSGestureHandler.addPointer(e.pointerId);
  44218. };
  44219. this._onGesture = function (e) {
  44220. _this.camera.radius *= e.scale;
  44221. if (e.preventDefault) {
  44222. if (!noPreventDefault) {
  44223. e.stopPropagation();
  44224. e.preventDefault();
  44225. }
  44226. }
  44227. };
  44228. element.addEventListener("mousemove", this._onMouseMove, false);
  44229. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44230. element.addEventListener("MSGestureChange", this._onGesture, false);
  44231. BABYLON.Tools.RegisterTopRootEvents([
  44232. { name: "blur", handler: this._onLostFocus }
  44233. ]);
  44234. };
  44235. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44236. if (this._onLostFocus) {
  44237. BABYLON.Tools.UnregisterTopRootEvents([
  44238. { name: "blur", handler: this._onLostFocus }
  44239. ]);
  44240. }
  44241. if (element && this._observer) {
  44242. this.camera.getScene().onPointerObservable.remove(this._observer);
  44243. this._observer = null;
  44244. if (this._onContextMenu) {
  44245. element.removeEventListener("contextmenu", this._onContextMenu);
  44246. }
  44247. if (this._onMouseMove) {
  44248. element.removeEventListener("mousemove", this._onMouseMove);
  44249. }
  44250. if (this._onGestureStart) {
  44251. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44252. }
  44253. if (this._onGesture) {
  44254. element.removeEventListener("MSGestureChange", this._onGesture);
  44255. }
  44256. this._isPanClick = false;
  44257. this.pinchInwards = true;
  44258. this._onMouseMove = null;
  44259. this._onGestureStart = null;
  44260. this._onGesture = null;
  44261. this._MSGestureHandler = null;
  44262. this._onLostFocus = null;
  44263. this._onContextMenu = null;
  44264. }
  44265. };
  44266. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44267. return "ArcRotateCameraPointersInput";
  44268. };
  44269. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44270. return "pointers";
  44271. };
  44272. __decorate([
  44273. BABYLON.serialize()
  44274. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44275. __decorate([
  44276. BABYLON.serialize()
  44277. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44278. __decorate([
  44279. BABYLON.serialize()
  44280. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44281. __decorate([
  44282. BABYLON.serialize()
  44283. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44284. __decorate([
  44285. BABYLON.serialize()
  44286. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44287. __decorate([
  44288. BABYLON.serialize()
  44289. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44290. __decorate([
  44291. BABYLON.serialize()
  44292. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44293. __decorate([
  44294. BABYLON.serialize()
  44295. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44296. return ArcRotateCameraPointersInput;
  44297. }());
  44298. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44299. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44300. })(BABYLON || (BABYLON = {}));
  44301. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44302. var BABYLON;
  44303. (function (BABYLON) {
  44304. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44305. __extends(ArcRotateCameraInputsManager, _super);
  44306. function ArcRotateCameraInputsManager(camera) {
  44307. return _super.call(this, camera) || this;
  44308. }
  44309. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44310. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44311. return this;
  44312. };
  44313. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44314. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44315. return this;
  44316. };
  44317. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44318. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44319. return this;
  44320. };
  44321. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44322. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44323. return this;
  44324. };
  44325. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44326. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44327. return this;
  44328. };
  44329. return ArcRotateCameraInputsManager;
  44330. }(BABYLON.CameraInputsManager));
  44331. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44332. })(BABYLON || (BABYLON = {}));
  44333. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44334. var BABYLON;
  44335. (function (BABYLON) {
  44336. var ArcRotateCamera = /** @class */ (function (_super) {
  44337. __extends(ArcRotateCamera, _super);
  44338. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44339. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44340. _this.inertialAlphaOffset = 0;
  44341. _this.inertialBetaOffset = 0;
  44342. _this.inertialRadiusOffset = 0;
  44343. _this.lowerAlphaLimit = null;
  44344. _this.upperAlphaLimit = null;
  44345. _this.lowerBetaLimit = 0.01;
  44346. _this.upperBetaLimit = Math.PI;
  44347. _this.lowerRadiusLimit = null;
  44348. _this.upperRadiusLimit = null;
  44349. _this.inertialPanningX = 0;
  44350. _this.inertialPanningY = 0;
  44351. _this.pinchToPanMaxDistance = 20;
  44352. _this.panningDistanceLimit = null;
  44353. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44354. _this.panningInertia = 0.9;
  44355. //-- end properties for backward compatibility for inputs
  44356. _this.zoomOnFactor = 1;
  44357. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44358. _this.allowUpsideDown = true;
  44359. _this._viewMatrix = new BABYLON.Matrix();
  44360. // Panning
  44361. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44362. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44363. _this.checkCollisions = false;
  44364. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44365. _this._previousPosition = BABYLON.Vector3.Zero();
  44366. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44367. _this._newPosition = BABYLON.Vector3.Zero();
  44368. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44369. if (collidedMesh === void 0) { collidedMesh = null; }
  44370. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44371. newPosition.multiplyInPlace(_this._collider._radius);
  44372. }
  44373. if (!collidedMesh) {
  44374. _this._previousPosition.copyFrom(_this.position);
  44375. }
  44376. else {
  44377. _this.setPosition(newPosition);
  44378. if (_this.onCollide) {
  44379. _this.onCollide(collidedMesh);
  44380. }
  44381. }
  44382. // Recompute because of constraints
  44383. var cosa = Math.cos(_this.alpha);
  44384. var sina = Math.sin(_this.alpha);
  44385. var cosb = Math.cos(_this.beta);
  44386. var sinb = Math.sin(_this.beta);
  44387. if (sinb === 0) {
  44388. sinb = 0.0001;
  44389. }
  44390. var target = _this._getTargetPosition();
  44391. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44392. _this.position.copyFrom(_this._newPosition);
  44393. var up = _this.upVector;
  44394. if (_this.allowUpsideDown && _this.beta < 0) {
  44395. up = up.clone();
  44396. up = up.negate();
  44397. }
  44398. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44399. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44400. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44401. _this._collisionTriggered = false;
  44402. };
  44403. _this._target = BABYLON.Vector3.Zero();
  44404. if (target) {
  44405. _this.setTarget(target);
  44406. }
  44407. _this.alpha = alpha;
  44408. _this.beta = beta;
  44409. _this.radius = radius;
  44410. _this.getViewMatrix();
  44411. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44412. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44413. return _this;
  44414. }
  44415. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44416. get: function () {
  44417. return this._target;
  44418. },
  44419. set: function (value) {
  44420. this.setTarget(value);
  44421. },
  44422. enumerable: true,
  44423. configurable: true
  44424. });
  44425. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44426. //-- begin properties for backward compatibility for inputs
  44427. get: function () {
  44428. var pointers = this.inputs.attached["pointers"];
  44429. if (pointers)
  44430. return pointers.angularSensibilityX;
  44431. return 0;
  44432. },
  44433. set: function (value) {
  44434. var pointers = this.inputs.attached["pointers"];
  44435. if (pointers) {
  44436. pointers.angularSensibilityX = value;
  44437. }
  44438. },
  44439. enumerable: true,
  44440. configurable: true
  44441. });
  44442. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44443. get: function () {
  44444. var pointers = this.inputs.attached["pointers"];
  44445. if (pointers)
  44446. return pointers.angularSensibilityY;
  44447. return 0;
  44448. },
  44449. set: function (value) {
  44450. var pointers = this.inputs.attached["pointers"];
  44451. if (pointers) {
  44452. pointers.angularSensibilityY = value;
  44453. }
  44454. },
  44455. enumerable: true,
  44456. configurable: true
  44457. });
  44458. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44459. get: function () {
  44460. var pointers = this.inputs.attached["pointers"];
  44461. if (pointers)
  44462. return pointers.pinchPrecision;
  44463. return 0;
  44464. },
  44465. set: function (value) {
  44466. var pointers = this.inputs.attached["pointers"];
  44467. if (pointers) {
  44468. pointers.pinchPrecision = value;
  44469. }
  44470. },
  44471. enumerable: true,
  44472. configurable: true
  44473. });
  44474. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44475. get: function () {
  44476. var pointers = this.inputs.attached["pointers"];
  44477. if (pointers)
  44478. return pointers.pinchDeltaPercentage;
  44479. return 0;
  44480. },
  44481. set: function (value) {
  44482. var pointers = this.inputs.attached["pointers"];
  44483. if (pointers) {
  44484. pointers.pinchDeltaPercentage = value;
  44485. }
  44486. },
  44487. enumerable: true,
  44488. configurable: true
  44489. });
  44490. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44491. get: function () {
  44492. var pointers = this.inputs.attached["pointers"];
  44493. if (pointers)
  44494. return pointers.panningSensibility;
  44495. return 0;
  44496. },
  44497. set: function (value) {
  44498. var pointers = this.inputs.attached["pointers"];
  44499. if (pointers) {
  44500. pointers.panningSensibility = value;
  44501. }
  44502. },
  44503. enumerable: true,
  44504. configurable: true
  44505. });
  44506. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44507. get: function () {
  44508. var keyboard = this.inputs.attached["keyboard"];
  44509. if (keyboard)
  44510. return keyboard.keysUp;
  44511. return [];
  44512. },
  44513. set: function (value) {
  44514. var keyboard = this.inputs.attached["keyboard"];
  44515. if (keyboard)
  44516. keyboard.keysUp = value;
  44517. },
  44518. enumerable: true,
  44519. configurable: true
  44520. });
  44521. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44522. get: function () {
  44523. var keyboard = this.inputs.attached["keyboard"];
  44524. if (keyboard)
  44525. return keyboard.keysDown;
  44526. return [];
  44527. },
  44528. set: function (value) {
  44529. var keyboard = this.inputs.attached["keyboard"];
  44530. if (keyboard)
  44531. keyboard.keysDown = value;
  44532. },
  44533. enumerable: true,
  44534. configurable: true
  44535. });
  44536. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44537. get: function () {
  44538. var keyboard = this.inputs.attached["keyboard"];
  44539. if (keyboard)
  44540. return keyboard.keysLeft;
  44541. return [];
  44542. },
  44543. set: function (value) {
  44544. var keyboard = this.inputs.attached["keyboard"];
  44545. if (keyboard)
  44546. keyboard.keysLeft = value;
  44547. },
  44548. enumerable: true,
  44549. configurable: true
  44550. });
  44551. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44552. get: function () {
  44553. var keyboard = this.inputs.attached["keyboard"];
  44554. if (keyboard)
  44555. return keyboard.keysRight;
  44556. return [];
  44557. },
  44558. set: function (value) {
  44559. var keyboard = this.inputs.attached["keyboard"];
  44560. if (keyboard)
  44561. keyboard.keysRight = value;
  44562. },
  44563. enumerable: true,
  44564. configurable: true
  44565. });
  44566. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44567. get: function () {
  44568. var mousewheel = this.inputs.attached["mousewheel"];
  44569. if (mousewheel)
  44570. return mousewheel.wheelPrecision;
  44571. return 0;
  44572. },
  44573. set: function (value) {
  44574. var mousewheel = this.inputs.attached["mousewheel"];
  44575. if (mousewheel)
  44576. mousewheel.wheelPrecision = value;
  44577. },
  44578. enumerable: true,
  44579. configurable: true
  44580. });
  44581. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44582. get: function () {
  44583. var mousewheel = this.inputs.attached["mousewheel"];
  44584. if (mousewheel)
  44585. return mousewheel.wheelDeltaPercentage;
  44586. return 0;
  44587. },
  44588. set: function (value) {
  44589. var mousewheel = this.inputs.attached["mousewheel"];
  44590. if (mousewheel)
  44591. mousewheel.wheelDeltaPercentage = value;
  44592. },
  44593. enumerable: true,
  44594. configurable: true
  44595. });
  44596. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44597. get: function () {
  44598. return this._bouncingBehavior;
  44599. },
  44600. enumerable: true,
  44601. configurable: true
  44602. });
  44603. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44604. get: function () {
  44605. return this._bouncingBehavior != null;
  44606. },
  44607. set: function (value) {
  44608. if (value === this.useBouncingBehavior) {
  44609. return;
  44610. }
  44611. if (value) {
  44612. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44613. this.addBehavior(this._bouncingBehavior);
  44614. }
  44615. else if (this._bouncingBehavior) {
  44616. this.removeBehavior(this._bouncingBehavior);
  44617. this._bouncingBehavior = null;
  44618. }
  44619. },
  44620. enumerable: true,
  44621. configurable: true
  44622. });
  44623. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44624. get: function () {
  44625. return this._framingBehavior;
  44626. },
  44627. enumerable: true,
  44628. configurable: true
  44629. });
  44630. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44631. get: function () {
  44632. return this._framingBehavior != null;
  44633. },
  44634. set: function (value) {
  44635. if (value === this.useFramingBehavior) {
  44636. return;
  44637. }
  44638. if (value) {
  44639. this._framingBehavior = new BABYLON.FramingBehavior();
  44640. this.addBehavior(this._framingBehavior);
  44641. }
  44642. else if (this._framingBehavior) {
  44643. this.removeBehavior(this._framingBehavior);
  44644. this._framingBehavior = null;
  44645. }
  44646. },
  44647. enumerable: true,
  44648. configurable: true
  44649. });
  44650. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44651. get: function () {
  44652. return this._autoRotationBehavior;
  44653. },
  44654. enumerable: true,
  44655. configurable: true
  44656. });
  44657. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44658. get: function () {
  44659. return this._autoRotationBehavior != null;
  44660. },
  44661. set: function (value) {
  44662. if (value === this.useAutoRotationBehavior) {
  44663. return;
  44664. }
  44665. if (value) {
  44666. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44667. this.addBehavior(this._autoRotationBehavior);
  44668. }
  44669. else if (this._autoRotationBehavior) {
  44670. this.removeBehavior(this._autoRotationBehavior);
  44671. this._autoRotationBehavior = null;
  44672. }
  44673. },
  44674. enumerable: true,
  44675. configurable: true
  44676. });
  44677. // Cache
  44678. ArcRotateCamera.prototype._initCache = function () {
  44679. _super.prototype._initCache.call(this);
  44680. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44681. this._cache.alpha = undefined;
  44682. this._cache.beta = undefined;
  44683. this._cache.radius = undefined;
  44684. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44685. };
  44686. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44687. if (!ignoreParentClass) {
  44688. _super.prototype._updateCache.call(this);
  44689. }
  44690. this._cache._target.copyFrom(this._getTargetPosition());
  44691. this._cache.alpha = this.alpha;
  44692. this._cache.beta = this.beta;
  44693. this._cache.radius = this.radius;
  44694. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44695. };
  44696. ArcRotateCamera.prototype._getTargetPosition = function () {
  44697. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44698. var pos = this._targetHost.getAbsolutePosition();
  44699. if (this._targetBoundingCenter) {
  44700. pos.addToRef(this._targetBoundingCenter, this._target);
  44701. }
  44702. else {
  44703. this._target.copyFrom(pos);
  44704. }
  44705. }
  44706. var lockedTargetPosition = this._getLockedTargetPosition();
  44707. if (lockedTargetPosition) {
  44708. return lockedTargetPosition;
  44709. }
  44710. return this._target;
  44711. };
  44712. ArcRotateCamera.prototype.storeState = function () {
  44713. this._storedAlpha = this.alpha;
  44714. this._storedBeta = this.beta;
  44715. this._storedRadius = this.radius;
  44716. this._storedTarget = this._getTargetPosition().clone();
  44717. return _super.prototype.storeState.call(this);
  44718. };
  44719. /**
  44720. * Restored camera state. You must call storeState() first
  44721. */
  44722. ArcRotateCamera.prototype._restoreStateValues = function () {
  44723. if (!_super.prototype._restoreStateValues.call(this)) {
  44724. return false;
  44725. }
  44726. this.alpha = this._storedAlpha;
  44727. this.beta = this._storedBeta;
  44728. this.radius = this._storedRadius;
  44729. this.setTarget(this._storedTarget.clone());
  44730. this.inertialAlphaOffset = 0;
  44731. this.inertialBetaOffset = 0;
  44732. this.inertialRadiusOffset = 0;
  44733. this.inertialPanningX = 0;
  44734. this.inertialPanningY = 0;
  44735. return true;
  44736. };
  44737. // Synchronized
  44738. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44739. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44740. return false;
  44741. return this._cache._target.equals(this._getTargetPosition())
  44742. && this._cache.alpha === this.alpha
  44743. && this._cache.beta === this.beta
  44744. && this._cache.radius === this.radius
  44745. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44746. };
  44747. // Methods
  44748. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44749. var _this = this;
  44750. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44751. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44752. this._useCtrlForPanning = useCtrlForPanning;
  44753. this._panningMouseButton = panningMouseButton;
  44754. this.inputs.attachElement(element, noPreventDefault);
  44755. this._reset = function () {
  44756. _this.inertialAlphaOffset = 0;
  44757. _this.inertialBetaOffset = 0;
  44758. _this.inertialRadiusOffset = 0;
  44759. _this.inertialPanningX = 0;
  44760. _this.inertialPanningY = 0;
  44761. };
  44762. };
  44763. ArcRotateCamera.prototype.detachControl = function (element) {
  44764. this.inputs.detachElement(element);
  44765. if (this._reset) {
  44766. this._reset();
  44767. }
  44768. };
  44769. ArcRotateCamera.prototype._checkInputs = function () {
  44770. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44771. if (this._collisionTriggered) {
  44772. return;
  44773. }
  44774. this.inputs.checkInputs();
  44775. // Inertia
  44776. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44777. if (this.getScene().useRightHandedSystem) {
  44778. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44779. }
  44780. else {
  44781. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44782. }
  44783. this.beta += this.inertialBetaOffset;
  44784. this.radius -= this.inertialRadiusOffset;
  44785. this.inertialAlphaOffset *= this.inertia;
  44786. this.inertialBetaOffset *= this.inertia;
  44787. this.inertialRadiusOffset *= this.inertia;
  44788. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44789. this.inertialAlphaOffset = 0;
  44790. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44791. this.inertialBetaOffset = 0;
  44792. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44793. this.inertialRadiusOffset = 0;
  44794. }
  44795. // Panning inertia
  44796. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44797. if (!this._localDirection) {
  44798. this._localDirection = BABYLON.Vector3.Zero();
  44799. this._transformedDirection = BABYLON.Vector3.Zero();
  44800. }
  44801. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44802. this._localDirection.multiplyInPlace(this.panningAxis);
  44803. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44804. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44805. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44806. if (!this.panningAxis.y) {
  44807. this._transformedDirection.y = 0;
  44808. }
  44809. if (!this._targetHost) {
  44810. if (this.panningDistanceLimit) {
  44811. this._transformedDirection.addInPlace(this._target);
  44812. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44813. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44814. this._target.copyFrom(this._transformedDirection);
  44815. }
  44816. }
  44817. else {
  44818. this._target.addInPlace(this._transformedDirection);
  44819. }
  44820. }
  44821. this.inertialPanningX *= this.panningInertia;
  44822. this.inertialPanningY *= this.panningInertia;
  44823. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44824. this.inertialPanningX = 0;
  44825. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44826. this.inertialPanningY = 0;
  44827. }
  44828. // Limits
  44829. this._checkLimits();
  44830. _super.prototype._checkInputs.call(this);
  44831. };
  44832. ArcRotateCamera.prototype._checkLimits = function () {
  44833. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44834. if (this.allowUpsideDown && this.beta > Math.PI) {
  44835. this.beta = this.beta - (2 * Math.PI);
  44836. }
  44837. }
  44838. else {
  44839. if (this.beta < this.lowerBetaLimit) {
  44840. this.beta = this.lowerBetaLimit;
  44841. }
  44842. }
  44843. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44844. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44845. this.beta = this.beta + (2 * Math.PI);
  44846. }
  44847. }
  44848. else {
  44849. if (this.beta > this.upperBetaLimit) {
  44850. this.beta = this.upperBetaLimit;
  44851. }
  44852. }
  44853. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44854. this.alpha = this.lowerAlphaLimit;
  44855. }
  44856. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44857. this.alpha = this.upperAlphaLimit;
  44858. }
  44859. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44860. this.radius = this.lowerRadiusLimit;
  44861. }
  44862. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44863. this.radius = this.upperRadiusLimit;
  44864. }
  44865. };
  44866. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44867. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44868. this.radius = radiusv3.length();
  44869. if (this.radius === 0) {
  44870. this.radius = 0.0001; // Just to avoid division by zero
  44871. }
  44872. // Alpha
  44873. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44874. if (radiusv3.z < 0) {
  44875. this.alpha = 2 * Math.PI - this.alpha;
  44876. }
  44877. // Beta
  44878. this.beta = Math.acos(radiusv3.y / this.radius);
  44879. this._checkLimits();
  44880. };
  44881. ArcRotateCamera.prototype.setPosition = function (position) {
  44882. if (this.position.equals(position)) {
  44883. return;
  44884. }
  44885. this.position.copyFrom(position);
  44886. this.rebuildAnglesAndRadius();
  44887. };
  44888. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44889. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44890. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44891. if (target.getBoundingInfo) {
  44892. if (toBoundingCenter) {
  44893. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44894. }
  44895. else {
  44896. this._targetBoundingCenter = null;
  44897. }
  44898. this._targetHost = target;
  44899. this._target = this._getTargetPosition();
  44900. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44901. }
  44902. else {
  44903. var newTarget = target;
  44904. var currentTarget = this._getTargetPosition();
  44905. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44906. return;
  44907. }
  44908. this._targetHost = null;
  44909. this._target = newTarget;
  44910. this._targetBoundingCenter = null;
  44911. this.onMeshTargetChangedObservable.notifyObservers(null);
  44912. }
  44913. this.rebuildAnglesAndRadius();
  44914. };
  44915. ArcRotateCamera.prototype._getViewMatrix = function () {
  44916. // Compute
  44917. var cosa = Math.cos(this.alpha);
  44918. var sina = Math.sin(this.alpha);
  44919. var cosb = Math.cos(this.beta);
  44920. var sinb = Math.sin(this.beta);
  44921. if (sinb === 0) {
  44922. sinb = 0.0001;
  44923. }
  44924. var target = this._getTargetPosition();
  44925. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44926. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44927. if (!this._collider) {
  44928. this._collider = new BABYLON.Collider();
  44929. }
  44930. this._collider._radius = this.collisionRadius;
  44931. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44932. this._collisionTriggered = true;
  44933. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44934. }
  44935. else {
  44936. this.position.copyFrom(this._newPosition);
  44937. var up = this.upVector;
  44938. if (this.allowUpsideDown && sinb < 0) {
  44939. up = up.clone();
  44940. up = up.negate();
  44941. }
  44942. if (this.getScene().useRightHandedSystem) {
  44943. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44944. }
  44945. else {
  44946. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44947. }
  44948. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44949. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44950. }
  44951. this._currentTarget = target;
  44952. return this._viewMatrix;
  44953. };
  44954. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44955. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44956. meshes = meshes || this.getScene().meshes;
  44957. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44958. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44959. this.radius = distance * this.zoomOnFactor;
  44960. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44961. };
  44962. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44963. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44964. var meshesOrMinMaxVector;
  44965. var distance;
  44966. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44967. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44968. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44969. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44970. }
  44971. else {
  44972. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44973. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44974. distance = minMaxVectorAndDistance.distance;
  44975. }
  44976. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44977. if (!doNotUpdateMaxZ) {
  44978. this.maxZ = distance * 2;
  44979. }
  44980. };
  44981. /**
  44982. * @override
  44983. * Override Camera.createRigCamera
  44984. */
  44985. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44986. var alphaShift = 0;
  44987. switch (this.cameraRigMode) {
  44988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44991. case BABYLON.Camera.RIG_MODE_VR:
  44992. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44993. break;
  44994. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44995. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44996. break;
  44997. }
  44998. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44999. rigCam._cameraRigParams = {};
  45000. return rigCam;
  45001. };
  45002. /**
  45003. * @override
  45004. * Override Camera._updateRigCameras
  45005. */
  45006. ArcRotateCamera.prototype._updateRigCameras = function () {
  45007. var camLeft = this._rigCameras[0];
  45008. var camRight = this._rigCameras[1];
  45009. camLeft.beta = camRight.beta = this.beta;
  45010. camLeft.radius = camRight.radius = this.radius;
  45011. switch (this.cameraRigMode) {
  45012. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45013. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45015. case BABYLON.Camera.RIG_MODE_VR:
  45016. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45017. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45018. break;
  45019. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45020. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45021. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45022. break;
  45023. }
  45024. _super.prototype._updateRigCameras.call(this);
  45025. };
  45026. ArcRotateCamera.prototype.dispose = function () {
  45027. this.inputs.clear();
  45028. _super.prototype.dispose.call(this);
  45029. };
  45030. ArcRotateCamera.prototype.getClassName = function () {
  45031. return "ArcRotateCamera";
  45032. };
  45033. __decorate([
  45034. BABYLON.serialize()
  45035. ], ArcRotateCamera.prototype, "alpha", void 0);
  45036. __decorate([
  45037. BABYLON.serialize()
  45038. ], ArcRotateCamera.prototype, "beta", void 0);
  45039. __decorate([
  45040. BABYLON.serialize()
  45041. ], ArcRotateCamera.prototype, "radius", void 0);
  45042. __decorate([
  45043. BABYLON.serializeAsVector3("target")
  45044. ], ArcRotateCamera.prototype, "_target", void 0);
  45045. __decorate([
  45046. BABYLON.serialize()
  45047. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45048. __decorate([
  45049. BABYLON.serialize()
  45050. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45051. __decorate([
  45052. BABYLON.serialize()
  45053. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45054. __decorate([
  45055. BABYLON.serialize()
  45056. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45057. __decorate([
  45058. BABYLON.serialize()
  45059. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45060. __decorate([
  45061. BABYLON.serialize()
  45062. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45063. __decorate([
  45064. BABYLON.serialize()
  45065. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45066. __decorate([
  45067. BABYLON.serialize()
  45068. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45069. __decorate([
  45070. BABYLON.serialize()
  45071. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45072. __decorate([
  45073. BABYLON.serialize()
  45074. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45075. __decorate([
  45076. BABYLON.serialize()
  45077. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45078. __decorate([
  45079. BABYLON.serialize()
  45080. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45081. __decorate([
  45082. BABYLON.serialize()
  45083. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45084. __decorate([
  45085. BABYLON.serializeAsVector3()
  45086. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45087. __decorate([
  45088. BABYLON.serialize()
  45089. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45090. __decorate([
  45091. BABYLON.serialize()
  45092. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45093. __decorate([
  45094. BABYLON.serialize()
  45095. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45096. return ArcRotateCamera;
  45097. }(BABYLON.TargetCamera));
  45098. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45099. })(BABYLON || (BABYLON = {}));
  45100. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45101. var BABYLON;
  45102. (function (BABYLON) {
  45103. /**
  45104. * The HemisphericLight simulates the ambient environment light,
  45105. * so the passed direction is the light reflection direction, not the incoming direction.
  45106. */
  45107. var HemisphericLight = /** @class */ (function (_super) {
  45108. __extends(HemisphericLight, _super);
  45109. /**
  45110. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45111. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45112. * The HemisphericLight can't cast shadows.
  45113. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45114. * @param name The friendly name of the light
  45115. * @param direction The direction of the light reflection
  45116. * @param scene The scene the light belongs to
  45117. */
  45118. function HemisphericLight(name, direction, scene) {
  45119. var _this = _super.call(this, name, scene) || this;
  45120. /**
  45121. * The groundColor is the light in the opposite direction to the one specified during creation.
  45122. * 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.
  45123. */
  45124. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45125. _this.direction = direction || BABYLON.Vector3.Up();
  45126. return _this;
  45127. }
  45128. HemisphericLight.prototype._buildUniformLayout = function () {
  45129. this._uniformBuffer.addUniform("vLightData", 4);
  45130. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45131. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45132. this._uniformBuffer.addUniform("vLightGround", 3);
  45133. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45134. this._uniformBuffer.addUniform("depthValues", 2);
  45135. this._uniformBuffer.create();
  45136. };
  45137. /**
  45138. * Returns the string "HemisphericLight".
  45139. * @return The class name
  45140. */
  45141. HemisphericLight.prototype.getClassName = function () {
  45142. return "HemisphericLight";
  45143. };
  45144. /**
  45145. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45146. * Returns the updated direction.
  45147. * @param target The target the direction should point to
  45148. * @return The computed direction
  45149. */
  45150. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45151. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45152. return this.direction;
  45153. };
  45154. /**
  45155. * Returns the shadow generator associated to the light.
  45156. * @returns Always null for hemispheric lights because it does not support shadows.
  45157. */
  45158. HemisphericLight.prototype.getShadowGenerator = function () {
  45159. return null;
  45160. };
  45161. /**
  45162. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45163. * @param effect The effect to update
  45164. * @param lightIndex The index of the light in the effect to update
  45165. * @returns The hemispheric light
  45166. */
  45167. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45168. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45169. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45170. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45171. return this;
  45172. };
  45173. /**
  45174. * @ignore internal use only.
  45175. */
  45176. HemisphericLight.prototype._getWorldMatrix = function () {
  45177. if (!this._worldMatrix) {
  45178. this._worldMatrix = BABYLON.Matrix.Identity();
  45179. }
  45180. return this._worldMatrix;
  45181. };
  45182. /**
  45183. * Returns the integer 3.
  45184. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45185. */
  45186. HemisphericLight.prototype.getTypeID = function () {
  45187. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45188. };
  45189. __decorate([
  45190. BABYLON.serializeAsColor3()
  45191. ], HemisphericLight.prototype, "groundColor", void 0);
  45192. __decorate([
  45193. BABYLON.serializeAsVector3()
  45194. ], HemisphericLight.prototype, "direction", void 0);
  45195. return HemisphericLight;
  45196. }(BABYLON.Light));
  45197. BABYLON.HemisphericLight = HemisphericLight;
  45198. })(BABYLON || (BABYLON = {}));
  45199. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45200. var BABYLON;
  45201. (function (BABYLON) {
  45202. /**
  45203. * Base implementation of @see IShadowLight
  45204. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45205. */
  45206. var ShadowLight = /** @class */ (function (_super) {
  45207. __extends(ShadowLight, _super);
  45208. function ShadowLight() {
  45209. var _this = _super !== null && _super.apply(this, arguments) || this;
  45210. _this._needProjectionMatrixCompute = true;
  45211. return _this;
  45212. }
  45213. ShadowLight.prototype._setPosition = function (value) {
  45214. this._position = value;
  45215. };
  45216. Object.defineProperty(ShadowLight.prototype, "position", {
  45217. /**
  45218. * Sets the position the shadow will be casted from. Also use as the light position for both
  45219. * point and spot lights.
  45220. */
  45221. get: function () {
  45222. return this._position;
  45223. },
  45224. /**
  45225. * Sets the position the shadow will be casted from. Also use as the light position for both
  45226. * point and spot lights.
  45227. */
  45228. set: function (value) {
  45229. this._setPosition(value);
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. ShadowLight.prototype._setDirection = function (value) {
  45235. this._direction = value;
  45236. };
  45237. Object.defineProperty(ShadowLight.prototype, "direction", {
  45238. /**
  45239. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45240. * Also use as the light direction on spot and directional lights.
  45241. */
  45242. get: function () {
  45243. return this._direction;
  45244. },
  45245. /**
  45246. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45247. * Also use as the light direction on spot and directional lights.
  45248. */
  45249. set: function (value) {
  45250. this._setDirection(value);
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45256. /**
  45257. * Gets the shadow projection clipping minimum z value.
  45258. */
  45259. get: function () {
  45260. return this._shadowMinZ;
  45261. },
  45262. /**
  45263. * Sets the shadow projection clipping minimum z value.
  45264. */
  45265. set: function (value) {
  45266. this._shadowMinZ = value;
  45267. this.forceProjectionMatrixCompute();
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45273. /**
  45274. * Sets the shadow projection clipping maximum z value.
  45275. */
  45276. get: function () {
  45277. return this._shadowMaxZ;
  45278. },
  45279. /**
  45280. * Gets the shadow projection clipping maximum z value.
  45281. */
  45282. set: function (value) {
  45283. this._shadowMaxZ = value;
  45284. this.forceProjectionMatrixCompute();
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. /**
  45290. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45291. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45292. */
  45293. ShadowLight.prototype.computeTransformedInformation = function () {
  45294. if (this.parent && this.parent.getWorldMatrix) {
  45295. if (!this.transformedPosition) {
  45296. this.transformedPosition = BABYLON.Vector3.Zero();
  45297. }
  45298. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45299. // In case the direction is present.
  45300. if (this.direction) {
  45301. if (!this.transformedDirection) {
  45302. this.transformedDirection = BABYLON.Vector3.Zero();
  45303. }
  45304. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45305. }
  45306. return true;
  45307. }
  45308. return false;
  45309. };
  45310. /**
  45311. * Return the depth scale used for the shadow map.
  45312. * @returns the depth scale.
  45313. */
  45314. ShadowLight.prototype.getDepthScale = function () {
  45315. return 50.0;
  45316. };
  45317. /**
  45318. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45319. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45320. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45321. */
  45322. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45323. return this.transformedDirection ? this.transformedDirection : this.direction;
  45324. };
  45325. /**
  45326. * Returns the ShadowLight absolute position in the World.
  45327. * @returns the position vector in world space
  45328. */
  45329. ShadowLight.prototype.getAbsolutePosition = function () {
  45330. return this.transformedPosition ? this.transformedPosition : this.position;
  45331. };
  45332. /**
  45333. * Sets the ShadowLight direction toward the passed target.
  45334. * @param target The point tot target in local space
  45335. * @returns the updated ShadowLight direction
  45336. */
  45337. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45338. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45339. return this.direction;
  45340. };
  45341. /**
  45342. * Returns the light rotation in euler definition.
  45343. * @returns the x y z rotation in local space.
  45344. */
  45345. ShadowLight.prototype.getRotation = function () {
  45346. this.direction.normalize();
  45347. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45348. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45349. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45350. };
  45351. /**
  45352. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45353. * @returns true if a cube texture needs to be use
  45354. */
  45355. ShadowLight.prototype.needCube = function () {
  45356. return false;
  45357. };
  45358. /**
  45359. * Detects if the projection matrix requires to be recomputed this frame.
  45360. * @returns true if it requires to be recomputed otherwise, false.
  45361. */
  45362. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45363. return this._needProjectionMatrixCompute;
  45364. };
  45365. /**
  45366. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45367. */
  45368. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45369. this._needProjectionMatrixCompute = true;
  45370. };
  45371. /**
  45372. * Get the world matrix of the sahdow lights.
  45373. * @ignore Internal Use Only
  45374. */
  45375. ShadowLight.prototype._getWorldMatrix = function () {
  45376. if (!this._worldMatrix) {
  45377. this._worldMatrix = BABYLON.Matrix.Identity();
  45378. }
  45379. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45380. return this._worldMatrix;
  45381. };
  45382. /**
  45383. * Gets the minZ used for shadow according to both the scene and the light.
  45384. * @param activeCamera The camera we are returning the min for
  45385. * @returns the depth min z
  45386. */
  45387. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45388. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45389. };
  45390. /**
  45391. * Gets the maxZ used for shadow according to both the scene and the light.
  45392. * @param activeCamera The camera we are returning the max for
  45393. * @returns the depth max z
  45394. */
  45395. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45396. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45397. };
  45398. /**
  45399. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45400. * @param matrix The materix to updated with the projection information
  45401. * @param viewMatrix The transform matrix of the light
  45402. * @param renderList The list of mesh to render in the map
  45403. * @returns The current light
  45404. */
  45405. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45406. if (this.customProjectionMatrixBuilder) {
  45407. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45408. }
  45409. else {
  45410. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45411. }
  45412. return this;
  45413. };
  45414. __decorate([
  45415. BABYLON.serializeAsVector3()
  45416. ], ShadowLight.prototype, "position", null);
  45417. __decorate([
  45418. BABYLON.serializeAsVector3()
  45419. ], ShadowLight.prototype, "direction", null);
  45420. __decorate([
  45421. BABYLON.serialize()
  45422. ], ShadowLight.prototype, "shadowMinZ", null);
  45423. __decorate([
  45424. BABYLON.serialize()
  45425. ], ShadowLight.prototype, "shadowMaxZ", null);
  45426. return ShadowLight;
  45427. }(BABYLON.Light));
  45428. BABYLON.ShadowLight = ShadowLight;
  45429. })(BABYLON || (BABYLON = {}));
  45430. //# sourceMappingURL=babylon.shadowLight.js.map
  45431. var BABYLON;
  45432. (function (BABYLON) {
  45433. /**
  45434. * A point light is a light defined by an unique point in world space.
  45435. * The light is emitted in every direction from this point.
  45436. * A good example of a point light is a standard light bulb.
  45437. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45438. */
  45439. var PointLight = /** @class */ (function (_super) {
  45440. __extends(PointLight, _super);
  45441. /**
  45442. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45443. * A PointLight emits the light in every direction.
  45444. * It can cast shadows.
  45445. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45446. * ```javascript
  45447. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45448. * ```
  45449. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45450. * @param name The light friendly name
  45451. * @param position The position of the point light in the scene
  45452. * @param scene The scene the lights belongs to
  45453. */
  45454. function PointLight(name, position, scene) {
  45455. var _this = _super.call(this, name, scene) || this;
  45456. _this._shadowAngle = Math.PI / 2;
  45457. _this.position = position;
  45458. return _this;
  45459. }
  45460. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45461. /**
  45462. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45463. * This specifies what angle the shadow will use to be created.
  45464. *
  45465. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45466. */
  45467. get: function () {
  45468. return this._shadowAngle;
  45469. },
  45470. /**
  45471. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45472. * This specifies what angle the shadow will use to be created.
  45473. *
  45474. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45475. */
  45476. set: function (value) {
  45477. this._shadowAngle = value;
  45478. this.forceProjectionMatrixCompute();
  45479. },
  45480. enumerable: true,
  45481. configurable: true
  45482. });
  45483. Object.defineProperty(PointLight.prototype, "direction", {
  45484. /**
  45485. * Gets the direction if it has been set.
  45486. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45487. */
  45488. get: function () {
  45489. return this._direction;
  45490. },
  45491. /**
  45492. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45493. */
  45494. set: function (value) {
  45495. var previousNeedCube = this.needCube();
  45496. this._direction = value;
  45497. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45498. this._shadowGenerator.recreateShadowMap();
  45499. }
  45500. },
  45501. enumerable: true,
  45502. configurable: true
  45503. });
  45504. /**
  45505. * Returns the string "PointLight"
  45506. * @returns the class name
  45507. */
  45508. PointLight.prototype.getClassName = function () {
  45509. return "PointLight";
  45510. };
  45511. /**
  45512. * Returns the integer 0.
  45513. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45514. */
  45515. PointLight.prototype.getTypeID = function () {
  45516. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45517. };
  45518. /**
  45519. * Specifies wether or not the shadowmap should be a cube texture.
  45520. * @returns true if the shadowmap needs to be a cube texture.
  45521. */
  45522. PointLight.prototype.needCube = function () {
  45523. return !this.direction;
  45524. };
  45525. /**
  45526. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45527. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45528. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45529. */
  45530. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45531. if (this.direction) {
  45532. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45533. }
  45534. else {
  45535. switch (faceIndex) {
  45536. case 0:
  45537. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45538. case 1:
  45539. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45540. case 2:
  45541. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45542. case 3:
  45543. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45544. case 4:
  45545. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45546. case 5:
  45547. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45548. }
  45549. }
  45550. return BABYLON.Vector3.Zero();
  45551. };
  45552. /**
  45553. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45554. * - fov = PI / 2
  45555. * - aspect ratio : 1.0
  45556. * - z-near and far equal to the active camera minZ and maxZ.
  45557. * Returns the PointLight.
  45558. */
  45559. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45560. var activeCamera = this.getScene().activeCamera;
  45561. if (!activeCamera) {
  45562. return;
  45563. }
  45564. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45565. };
  45566. PointLight.prototype._buildUniformLayout = function () {
  45567. this._uniformBuffer.addUniform("vLightData", 4);
  45568. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45569. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45570. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45571. this._uniformBuffer.addUniform("depthValues", 2);
  45572. this._uniformBuffer.create();
  45573. };
  45574. /**
  45575. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45576. * @param effect The effect to update
  45577. * @param lightIndex The index of the light in the effect to update
  45578. * @returns The point light
  45579. */
  45580. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45581. if (this.computeTransformedInformation()) {
  45582. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45583. return this;
  45584. }
  45585. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45586. return this;
  45587. };
  45588. __decorate([
  45589. BABYLON.serialize()
  45590. ], PointLight.prototype, "shadowAngle", null);
  45591. return PointLight;
  45592. }(BABYLON.ShadowLight));
  45593. BABYLON.PointLight = PointLight;
  45594. })(BABYLON || (BABYLON = {}));
  45595. //# sourceMappingURL=babylon.pointLight.js.map
  45596. var BABYLON;
  45597. (function (BABYLON) {
  45598. /**
  45599. * A directional light is defined by a direction (what a surprise!).
  45600. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45601. * 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.
  45602. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45603. */
  45604. var DirectionalLight = /** @class */ (function (_super) {
  45605. __extends(DirectionalLight, _super);
  45606. /**
  45607. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45608. * The directional light is emitted from everywhere in the given direction.
  45609. * It can cast shawdows.
  45610. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45611. * @param name The friendly name of the light
  45612. * @param direction The direction of the light
  45613. * @param scene The scene the light belongs to
  45614. */
  45615. function DirectionalLight(name, direction, scene) {
  45616. var _this = _super.call(this, name, scene) || this;
  45617. _this._shadowFrustumSize = 0;
  45618. _this._shadowOrthoScale = 0.5;
  45619. /**
  45620. * Automatically compute the projection matrix to best fit (including all the casters)
  45621. * on each frame.
  45622. */
  45623. _this.autoUpdateExtends = true;
  45624. // Cache
  45625. _this._orthoLeft = Number.MAX_VALUE;
  45626. _this._orthoRight = Number.MIN_VALUE;
  45627. _this._orthoTop = Number.MIN_VALUE;
  45628. _this._orthoBottom = Number.MAX_VALUE;
  45629. _this.position = direction.scale(-1.0);
  45630. _this.direction = direction;
  45631. return _this;
  45632. }
  45633. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45634. /**
  45635. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45636. */
  45637. get: function () {
  45638. return this._shadowFrustumSize;
  45639. },
  45640. /**
  45641. * Specifies a fix frustum size for the shadow generation.
  45642. */
  45643. set: function (value) {
  45644. this._shadowFrustumSize = value;
  45645. this.forceProjectionMatrixCompute();
  45646. },
  45647. enumerable: true,
  45648. configurable: true
  45649. });
  45650. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45651. /**
  45652. * Gets the shadow projection scale against the optimal computed one.
  45653. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45654. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45655. */
  45656. get: function () {
  45657. return this._shadowOrthoScale;
  45658. },
  45659. /**
  45660. * Sets the shadow projection scale against the optimal computed one.
  45661. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45662. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45663. */
  45664. set: function (value) {
  45665. this._shadowOrthoScale = value;
  45666. this.forceProjectionMatrixCompute();
  45667. },
  45668. enumerable: true,
  45669. configurable: true
  45670. });
  45671. /**
  45672. * Returns the string "DirectionalLight".
  45673. * @return The class name
  45674. */
  45675. DirectionalLight.prototype.getClassName = function () {
  45676. return "DirectionalLight";
  45677. };
  45678. /**
  45679. * Returns the integer 1.
  45680. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45681. */
  45682. DirectionalLight.prototype.getTypeID = function () {
  45683. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45684. };
  45685. /**
  45686. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45687. * Returns the DirectionalLight Shadow projection matrix.
  45688. */
  45689. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45690. if (this.shadowFrustumSize > 0) {
  45691. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45692. }
  45693. else {
  45694. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45695. }
  45696. };
  45697. /**
  45698. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45699. * Returns the DirectionalLight Shadow projection matrix.
  45700. */
  45701. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45702. var activeCamera = this.getScene().activeCamera;
  45703. if (!activeCamera) {
  45704. return;
  45705. }
  45706. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45707. };
  45708. /**
  45709. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45710. * Returns the DirectionalLight Shadow projection matrix.
  45711. */
  45712. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45713. var activeCamera = this.getScene().activeCamera;
  45714. if (!activeCamera) {
  45715. return;
  45716. }
  45717. // Check extends
  45718. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45719. var tempVector3 = BABYLON.Vector3.Zero();
  45720. this._orthoLeft = Number.MAX_VALUE;
  45721. this._orthoRight = Number.MIN_VALUE;
  45722. this._orthoTop = Number.MIN_VALUE;
  45723. this._orthoBottom = Number.MAX_VALUE;
  45724. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45725. var mesh = renderList[meshIndex];
  45726. if (!mesh) {
  45727. continue;
  45728. }
  45729. var boundingInfo = mesh.getBoundingInfo();
  45730. var boundingBox = boundingInfo.boundingBox;
  45731. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45732. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45733. if (tempVector3.x < this._orthoLeft)
  45734. this._orthoLeft = tempVector3.x;
  45735. if (tempVector3.y < this._orthoBottom)
  45736. this._orthoBottom = tempVector3.y;
  45737. if (tempVector3.x > this._orthoRight)
  45738. this._orthoRight = tempVector3.x;
  45739. if (tempVector3.y > this._orthoTop)
  45740. this._orthoTop = tempVector3.y;
  45741. }
  45742. }
  45743. }
  45744. var xOffset = this._orthoRight - this._orthoLeft;
  45745. var yOffset = this._orthoTop - this._orthoBottom;
  45746. 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);
  45747. };
  45748. DirectionalLight.prototype._buildUniformLayout = function () {
  45749. this._uniformBuffer.addUniform("vLightData", 4);
  45750. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45751. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45752. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45753. this._uniformBuffer.addUniform("depthValues", 2);
  45754. this._uniformBuffer.create();
  45755. };
  45756. /**
  45757. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45758. * @param effect The effect to update
  45759. * @param lightIndex The index of the light in the effect to update
  45760. * @returns The directional light
  45761. */
  45762. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45763. if (this.computeTransformedInformation()) {
  45764. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45765. return this;
  45766. }
  45767. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45768. return this;
  45769. };
  45770. /**
  45771. * Gets the minZ used for shadow according to both the scene and the light.
  45772. *
  45773. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45774. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45775. * @param activeCamera The camera we are returning the min for
  45776. * @returns the depth min z
  45777. */
  45778. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45779. return 1;
  45780. };
  45781. /**
  45782. * Gets the maxZ used for shadow according to both the scene and the light.
  45783. *
  45784. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45785. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45786. * @param activeCamera The camera we are returning the max for
  45787. * @returns the depth max z
  45788. */
  45789. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45790. return 1;
  45791. };
  45792. __decorate([
  45793. BABYLON.serialize()
  45794. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45795. __decorate([
  45796. BABYLON.serialize()
  45797. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45798. __decorate([
  45799. BABYLON.serialize()
  45800. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45801. return DirectionalLight;
  45802. }(BABYLON.ShadowLight));
  45803. BABYLON.DirectionalLight = DirectionalLight;
  45804. })(BABYLON || (BABYLON = {}));
  45805. //# sourceMappingURL=babylon.directionalLight.js.map
  45806. var BABYLON;
  45807. (function (BABYLON) {
  45808. /**
  45809. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45810. * These values define a cone of light starting from the position, emitting toward the direction.
  45811. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45812. * and the exponent defines the speed of the decay of the light with distance (reach).
  45813. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45814. */
  45815. var SpotLight = /** @class */ (function (_super) {
  45816. __extends(SpotLight, _super);
  45817. /**
  45818. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45819. * It can cast shadows.
  45820. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45821. * @param name The light friendly name
  45822. * @param position The position of the spot light in the scene
  45823. * @param direction The direction of the light in the scene
  45824. * @param angle The cone angle of the light in Radians
  45825. * @param exponent The light decay speed with the distance from the emission spot
  45826. * @param scene The scene the lights belongs to
  45827. */
  45828. function SpotLight(name, position, direction, angle, exponent, scene) {
  45829. var _this = _super.call(this, name, scene) || this;
  45830. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45831. _this._projectionTextureLightNear = 1e-6;
  45832. _this._projectionTextureLightFar = 1000.0;
  45833. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45834. _this._projectionTextureViewLightDirty = true;
  45835. _this._projectionTextureProjectionLightDirty = true;
  45836. _this._projectionTextureDirty = true;
  45837. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45838. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45839. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45840. _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);
  45841. _this.position = position;
  45842. _this.direction = direction;
  45843. _this.angle = angle;
  45844. _this.exponent = exponent;
  45845. return _this;
  45846. }
  45847. Object.defineProperty(SpotLight.prototype, "angle", {
  45848. /**
  45849. * Gets the cone angle of the spot light in Radians.
  45850. */
  45851. get: function () {
  45852. return this._angle;
  45853. },
  45854. /**
  45855. * Sets the cone angle of the spot light in Radians.
  45856. */
  45857. set: function (value) {
  45858. this._angle = value;
  45859. this._projectionTextureProjectionLightDirty = true;
  45860. this.forceProjectionMatrixCompute();
  45861. },
  45862. enumerable: true,
  45863. configurable: true
  45864. });
  45865. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45866. /**
  45867. * Allows scaling the angle of the light for shadow generation only.
  45868. */
  45869. get: function () {
  45870. return this._shadowAngleScale;
  45871. },
  45872. /**
  45873. * Allows scaling the angle of the light for shadow generation only.
  45874. */
  45875. set: function (value) {
  45876. this._shadowAngleScale = value;
  45877. this.forceProjectionMatrixCompute();
  45878. },
  45879. enumerable: true,
  45880. configurable: true
  45881. });
  45882. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45883. /**
  45884. * Allows reading the projecton texture
  45885. */
  45886. get: function () {
  45887. return this._projectionTextureMatrix;
  45888. },
  45889. enumerable: true,
  45890. configurable: true
  45891. });
  45892. ;
  45893. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45894. /**
  45895. * Gets the near clip of the Spotlight for texture projection.
  45896. */
  45897. get: function () {
  45898. return this._projectionTextureLightNear;
  45899. },
  45900. /**
  45901. * Sets the near clip of the Spotlight for texture projection.
  45902. */
  45903. set: function (value) {
  45904. this._projectionTextureLightNear = value;
  45905. this._projectionTextureProjectionLightDirty = true;
  45906. },
  45907. enumerable: true,
  45908. configurable: true
  45909. });
  45910. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45911. /**
  45912. * Gets the far clip of the Spotlight for texture projection.
  45913. */
  45914. get: function () {
  45915. return this._projectionTextureLightFar;
  45916. },
  45917. /**
  45918. * Sets the far clip of the Spotlight for texture projection.
  45919. */
  45920. set: function (value) {
  45921. this._projectionTextureLightFar = value;
  45922. this._projectionTextureProjectionLightDirty = true;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45928. /**
  45929. * Gets the Up vector of the Spotlight for texture projection.
  45930. */
  45931. get: function () {
  45932. return this._projectionTextureUpDirection;
  45933. },
  45934. /**
  45935. * Sets the Up vector of the Spotlight for texture projection.
  45936. */
  45937. set: function (value) {
  45938. this._projectionTextureUpDirection = value;
  45939. this._projectionTextureProjectionLightDirty = true;
  45940. },
  45941. enumerable: true,
  45942. configurable: true
  45943. });
  45944. ;
  45945. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45946. /**
  45947. * Gets the projection texture of the light.
  45948. */
  45949. get: function () {
  45950. return this._projectionTexture;
  45951. },
  45952. /**
  45953. * Sets the projection texture of the light.
  45954. */
  45955. set: function (value) {
  45956. this._projectionTexture = value;
  45957. this._projectionTextureDirty = true;
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. /**
  45963. * Returns the string "SpotLight".
  45964. * @returns the class name
  45965. */
  45966. SpotLight.prototype.getClassName = function () {
  45967. return "SpotLight";
  45968. };
  45969. /**
  45970. * Returns the integer 2.
  45971. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45972. */
  45973. SpotLight.prototype.getTypeID = function () {
  45974. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45975. };
  45976. /**
  45977. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45978. */
  45979. SpotLight.prototype._setDirection = function (value) {
  45980. _super.prototype._setDirection.call(this, value);
  45981. this._projectionTextureViewLightDirty = true;
  45982. };
  45983. /**
  45984. * Overrides the position setter to recompute the projection texture view light Matrix.
  45985. */
  45986. SpotLight.prototype._setPosition = function (value) {
  45987. _super.prototype._setPosition.call(this, value);
  45988. this._projectionTextureViewLightDirty = true;
  45989. };
  45990. /**
  45991. * 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.
  45992. * Returns the SpotLight.
  45993. */
  45994. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45995. var activeCamera = this.getScene().activeCamera;
  45996. if (!activeCamera) {
  45997. return;
  45998. }
  45999. this._shadowAngleScale = this._shadowAngleScale || 1;
  46000. var angle = this._shadowAngleScale * this._angle;
  46001. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46002. };
  46003. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46004. this._projectionTextureViewLightDirty = false;
  46005. this._projectionTextureDirty = true;
  46006. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46007. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46008. };
  46009. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46010. this._projectionTextureProjectionLightDirty = false;
  46011. this._projectionTextureDirty = true;
  46012. var light_far = this.projectionTextureLightFar;
  46013. var light_near = this.projectionTextureLightNear;
  46014. var P = light_far / (light_far - light_near);
  46015. var Q = -P * light_near;
  46016. var S = 1.0 / Math.tan(this._angle / 2.0);
  46017. var A = 1.0;
  46018. 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);
  46019. };
  46020. /**
  46021. * Main function for light texture projection matrix computing.
  46022. */
  46023. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46024. this._projectionTextureDirty = false;
  46025. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46026. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46027. };
  46028. SpotLight.prototype._buildUniformLayout = function () {
  46029. this._uniformBuffer.addUniform("vLightData", 4);
  46030. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46031. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46032. this._uniformBuffer.addUniform("vLightDirection", 3);
  46033. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46034. this._uniformBuffer.addUniform("depthValues", 2);
  46035. this._uniformBuffer.create();
  46036. };
  46037. /**
  46038. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46039. * @param effect The effect to update
  46040. * @param lightIndex The index of the light in the effect to update
  46041. * @returns The spot light
  46042. */
  46043. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46044. var normalizeDirection;
  46045. if (this.computeTransformedInformation()) {
  46046. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46047. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46048. }
  46049. else {
  46050. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46051. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46052. }
  46053. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46054. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46055. if (this._projectionTextureViewLightDirty) {
  46056. this._computeProjectionTextureViewLightMatrix();
  46057. }
  46058. if (this._projectionTextureProjectionLightDirty) {
  46059. this._computeProjectionTextureProjectionLightMatrix();
  46060. }
  46061. if (this._projectionTextureDirty) {
  46062. this._computeProjectionTextureMatrix();
  46063. }
  46064. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46065. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46066. }
  46067. return this;
  46068. };
  46069. /**
  46070. * Disposes the light and the associated resources.
  46071. */
  46072. SpotLight.prototype.dispose = function () {
  46073. _super.prototype.dispose.call(this);
  46074. if (this._projectionTexture) {
  46075. this._projectionTexture.dispose();
  46076. }
  46077. };
  46078. __decorate([
  46079. BABYLON.serialize()
  46080. ], SpotLight.prototype, "angle", null);
  46081. __decorate([
  46082. BABYLON.serialize()
  46083. ], SpotLight.prototype, "shadowAngleScale", null);
  46084. __decorate([
  46085. BABYLON.serialize()
  46086. ], SpotLight.prototype, "exponent", void 0);
  46087. __decorate([
  46088. BABYLON.serialize()
  46089. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46090. __decorate([
  46091. BABYLON.serialize()
  46092. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46093. __decorate([
  46094. BABYLON.serialize()
  46095. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46096. __decorate([
  46097. BABYLON.serializeAsTexture("projectedLightTexture")
  46098. ], SpotLight.prototype, "_projectionTexture", void 0);
  46099. return SpotLight;
  46100. }(BABYLON.ShadowLight));
  46101. BABYLON.SpotLight = SpotLight;
  46102. })(BABYLON || (BABYLON = {}));
  46103. //# sourceMappingURL=babylon.spotLight.js.map
  46104. var BABYLON;
  46105. (function (BABYLON) {
  46106. /**
  46107. * Class used to override all child animations of a given target
  46108. */
  46109. var AnimationPropertiesOverride = /** @class */ (function () {
  46110. function AnimationPropertiesOverride() {
  46111. /**
  46112. * Gets or sets a value indicating if animation blending must be used
  46113. */
  46114. this.enableBlending = false;
  46115. /**
  46116. * Gets or sets the blending speed to use when enableBlending is true
  46117. */
  46118. this.blendingSpeed = 0.01;
  46119. /**
  46120. * Gets or sets the default loop mode to use
  46121. */
  46122. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46123. }
  46124. return AnimationPropertiesOverride;
  46125. }());
  46126. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46127. })(BABYLON || (BABYLON = {}));
  46128. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46129. var BABYLON;
  46130. (function (BABYLON) {
  46131. var AnimationRange = /** @class */ (function () {
  46132. function AnimationRange(name, from, to) {
  46133. this.name = name;
  46134. this.from = from;
  46135. this.to = to;
  46136. }
  46137. AnimationRange.prototype.clone = function () {
  46138. return new AnimationRange(this.name, this.from, this.to);
  46139. };
  46140. return AnimationRange;
  46141. }());
  46142. BABYLON.AnimationRange = AnimationRange;
  46143. /**
  46144. * Composed of a frame, and an action function
  46145. */
  46146. var AnimationEvent = /** @class */ (function () {
  46147. function AnimationEvent(frame, action, onlyOnce) {
  46148. this.frame = frame;
  46149. this.action = action;
  46150. this.onlyOnce = onlyOnce;
  46151. this.isDone = false;
  46152. }
  46153. return AnimationEvent;
  46154. }());
  46155. BABYLON.AnimationEvent = AnimationEvent;
  46156. var PathCursor = /** @class */ (function () {
  46157. function PathCursor(path) {
  46158. this.path = path;
  46159. this._onchange = new Array();
  46160. this.value = 0;
  46161. this.animations = new Array();
  46162. }
  46163. PathCursor.prototype.getPoint = function () {
  46164. var point = this.path.getPointAtLengthPosition(this.value);
  46165. return new BABYLON.Vector3(point.x, 0, point.y);
  46166. };
  46167. PathCursor.prototype.moveAhead = function (step) {
  46168. if (step === void 0) { step = 0.002; }
  46169. this.move(step);
  46170. return this;
  46171. };
  46172. PathCursor.prototype.moveBack = function (step) {
  46173. if (step === void 0) { step = 0.002; }
  46174. this.move(-step);
  46175. return this;
  46176. };
  46177. PathCursor.prototype.move = function (step) {
  46178. if (Math.abs(step) > 1) {
  46179. throw "step size should be less than 1.";
  46180. }
  46181. this.value += step;
  46182. this.ensureLimits();
  46183. this.raiseOnChange();
  46184. return this;
  46185. };
  46186. PathCursor.prototype.ensureLimits = function () {
  46187. while (this.value > 1) {
  46188. this.value -= 1;
  46189. }
  46190. while (this.value < 0) {
  46191. this.value += 1;
  46192. }
  46193. return this;
  46194. };
  46195. // used by animation engine
  46196. PathCursor.prototype.raiseOnChange = function () {
  46197. var _this = this;
  46198. this._onchange.forEach(function (f) { return f(_this); });
  46199. return this;
  46200. };
  46201. PathCursor.prototype.onchange = function (f) {
  46202. this._onchange.push(f);
  46203. return this;
  46204. };
  46205. return PathCursor;
  46206. }());
  46207. BABYLON.PathCursor = PathCursor;
  46208. var AnimationKeyInterpolation;
  46209. (function (AnimationKeyInterpolation) {
  46210. /**
  46211. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46212. */
  46213. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46214. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46215. var Animation = /** @class */ (function () {
  46216. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46217. this.name = name;
  46218. this.targetProperty = targetProperty;
  46219. this.framePerSecond = framePerSecond;
  46220. this.dataType = dataType;
  46221. this.loopMode = loopMode;
  46222. this.enableBlending = enableBlending;
  46223. this._runtimeAnimations = new Array();
  46224. // The set of event that will be linked to this animation
  46225. this._events = new Array();
  46226. this.blendingSpeed = 0.01;
  46227. this._ranges = {};
  46228. this.targetPropertyPath = targetProperty.split(".");
  46229. this.dataType = dataType;
  46230. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46231. }
  46232. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46233. var dataType = undefined;
  46234. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46235. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46236. }
  46237. else if (from instanceof BABYLON.Quaternion) {
  46238. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46239. }
  46240. else if (from instanceof BABYLON.Vector3) {
  46241. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46242. }
  46243. else if (from instanceof BABYLON.Vector2) {
  46244. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46245. }
  46246. else if (from instanceof BABYLON.Color3) {
  46247. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46248. }
  46249. else if (from instanceof BABYLON.Size) {
  46250. dataType = Animation.ANIMATIONTYPE_SIZE;
  46251. }
  46252. if (dataType == undefined) {
  46253. return null;
  46254. }
  46255. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46256. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46257. animation.setKeys(keys);
  46258. if (easingFunction !== undefined) {
  46259. animation.setEasingFunction(easingFunction);
  46260. }
  46261. return animation;
  46262. };
  46263. /**
  46264. * Sets up an animation.
  46265. * @param property the property to animate
  46266. * @param animationType the animation type to apply
  46267. * @param easingFunction the easing function used in the animation
  46268. * @returns The created animation
  46269. */
  46270. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46271. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46272. animation.setEasingFunction(easingFunction);
  46273. return animation;
  46274. };
  46275. /**
  46276. * Create and start an animation on a node
  46277. * @param {string} name defines the name of the global animation that will be run on all nodes
  46278. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46279. * @param {string} targetProperty defines property to animate
  46280. * @param {number} framePerSecond defines the number of frame per second yo use
  46281. * @param {number} totalFrame defines the number of frames in total
  46282. * @param {any} from defines the initial value
  46283. * @param {any} to defines the final value
  46284. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46285. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46286. * @param onAnimationEnd defines the callback to call when animation end
  46287. * @returns the animatable created for this animation
  46288. */
  46289. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46290. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46291. if (!animation) {
  46292. return null;
  46293. }
  46294. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46295. };
  46296. /**
  46297. * Create and start an animation on a node and its descendants
  46298. * @param {string} name defines the name of the global animation that will be run on all nodes
  46299. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46300. * @param {boolean} 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.
  46301. * @param {string} targetProperty defines property to animate
  46302. * @param {number} framePerSecond defines the number of frame per second yo use
  46303. * @param {number} totalFrame defines the number of frames in total
  46304. * @param {any} from defines the initial value
  46305. * @param {any} to defines the final value
  46306. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46307. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46308. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46309. * @returns the list of animatables created for all nodes
  46310. * @example https://www.babylonjs-playground.com/#MH0VLI
  46311. */
  46312. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46313. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46314. if (!animation) {
  46315. return null;
  46316. }
  46317. var scene = node.getScene();
  46318. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46319. };
  46320. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46321. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46322. if (!animation) {
  46323. return null;
  46324. }
  46325. node.animations.push(animation);
  46326. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46327. };
  46328. /**
  46329. * Transition property of the Camera to the target Value.
  46330. * @param property The property to transition
  46331. * @param targetValue The target Value of the property
  46332. * @param host The object where the property to animate belongs
  46333. * @param scene Scene used to run the animation
  46334. * @param frameRate Framerate (in frame/s) to use
  46335. * @param transition The transition type we want to use
  46336. * @param duration The duration of the animation, in milliseconds
  46337. * @param onAnimationEnd Call back trigger at the end of the animation.
  46338. */
  46339. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46340. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46341. if (duration <= 0) {
  46342. host[property] = targetValue;
  46343. if (onAnimationEnd) {
  46344. onAnimationEnd();
  46345. }
  46346. return null;
  46347. }
  46348. var endFrame = frameRate * (duration / 1000);
  46349. transition.setKeys([{
  46350. frame: 0,
  46351. value: host[property].clone ? host[property].clone() : host[property]
  46352. },
  46353. {
  46354. frame: endFrame,
  46355. value: targetValue
  46356. }]);
  46357. if (!host.animations) {
  46358. host.animations = [];
  46359. }
  46360. host.animations.push(transition);
  46361. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46362. animation.onAnimationEnd = onAnimationEnd;
  46363. return animation;
  46364. };
  46365. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46366. /**
  46367. * Return the array of runtime animations currently using this animation
  46368. */
  46369. get: function () {
  46370. return this._runtimeAnimations;
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46376. get: function () {
  46377. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46378. var runtimeAnimation = _a[_i];
  46379. if (!runtimeAnimation.isStopped) {
  46380. return true;
  46381. }
  46382. }
  46383. return false;
  46384. },
  46385. enumerable: true,
  46386. configurable: true
  46387. });
  46388. // Methods
  46389. /**
  46390. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46391. */
  46392. Animation.prototype.toString = function (fullDetails) {
  46393. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46394. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46395. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46396. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46397. if (fullDetails) {
  46398. ret += ", Ranges: {";
  46399. var first = true;
  46400. for (var name in this._ranges) {
  46401. if (first) {
  46402. ret += ", ";
  46403. first = false;
  46404. }
  46405. ret += name;
  46406. }
  46407. ret += "}";
  46408. }
  46409. return ret;
  46410. };
  46411. /**
  46412. * Add an event to this animation.
  46413. */
  46414. Animation.prototype.addEvent = function (event) {
  46415. this._events.push(event);
  46416. };
  46417. /**
  46418. * Remove all events found at the given frame
  46419. * @param frame
  46420. */
  46421. Animation.prototype.removeEvents = function (frame) {
  46422. for (var index = 0; index < this._events.length; index++) {
  46423. if (this._events[index].frame === frame) {
  46424. this._events.splice(index, 1);
  46425. index--;
  46426. }
  46427. }
  46428. };
  46429. Animation.prototype.getEvents = function () {
  46430. return this._events;
  46431. };
  46432. Animation.prototype.createRange = function (name, from, to) {
  46433. // check name not already in use; could happen for bones after serialized
  46434. if (!this._ranges[name]) {
  46435. this._ranges[name] = new AnimationRange(name, from, to);
  46436. }
  46437. };
  46438. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46439. if (deleteFrames === void 0) { deleteFrames = true; }
  46440. var range = this._ranges[name];
  46441. if (!range) {
  46442. return;
  46443. }
  46444. if (deleteFrames) {
  46445. var from = range.from;
  46446. var to = range.to;
  46447. // this loop MUST go high to low for multiple splices to work
  46448. for (var key = this._keys.length - 1; key >= 0; key--) {
  46449. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46450. this._keys.splice(key, 1);
  46451. }
  46452. }
  46453. }
  46454. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46455. };
  46456. Animation.prototype.getRange = function (name) {
  46457. return this._ranges[name];
  46458. };
  46459. Animation.prototype.getKeys = function () {
  46460. return this._keys;
  46461. };
  46462. Animation.prototype.getHighestFrame = function () {
  46463. var ret = 0;
  46464. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46465. if (ret < this._keys[key].frame) {
  46466. ret = this._keys[key].frame;
  46467. }
  46468. }
  46469. return ret;
  46470. };
  46471. Animation.prototype.getEasingFunction = function () {
  46472. return this._easingFunction;
  46473. };
  46474. Animation.prototype.setEasingFunction = function (easingFunction) {
  46475. this._easingFunction = easingFunction;
  46476. };
  46477. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46478. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46479. };
  46480. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46481. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46482. };
  46483. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46484. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46485. };
  46486. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46487. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46488. };
  46489. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46490. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46491. };
  46492. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46493. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46494. };
  46495. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46496. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46497. };
  46498. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46499. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46500. };
  46501. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46502. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46503. };
  46504. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46505. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46506. };
  46507. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46508. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46509. };
  46510. Animation.prototype.clone = function () {
  46511. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46512. clone.enableBlending = this.enableBlending;
  46513. clone.blendingSpeed = this.blendingSpeed;
  46514. if (this._keys) {
  46515. clone.setKeys(this._keys);
  46516. }
  46517. if (this._ranges) {
  46518. clone._ranges = {};
  46519. for (var name in this._ranges) {
  46520. var range = this._ranges[name];
  46521. if (!range) {
  46522. continue;
  46523. }
  46524. clone._ranges[name] = range.clone();
  46525. }
  46526. }
  46527. return clone;
  46528. };
  46529. Animation.prototype.setKeys = function (values) {
  46530. this._keys = values.slice(0);
  46531. };
  46532. Animation.prototype.serialize = function () {
  46533. var serializationObject = {};
  46534. serializationObject.name = this.name;
  46535. serializationObject.property = this.targetProperty;
  46536. serializationObject.framePerSecond = this.framePerSecond;
  46537. serializationObject.dataType = this.dataType;
  46538. serializationObject.loopBehavior = this.loopMode;
  46539. serializationObject.enableBlending = this.enableBlending;
  46540. serializationObject.blendingSpeed = this.blendingSpeed;
  46541. var dataType = this.dataType;
  46542. serializationObject.keys = [];
  46543. var keys = this.getKeys();
  46544. for (var index = 0; index < keys.length; index++) {
  46545. var animationKey = keys[index];
  46546. var key = {};
  46547. key.frame = animationKey.frame;
  46548. switch (dataType) {
  46549. case Animation.ANIMATIONTYPE_FLOAT:
  46550. key.values = [animationKey.value];
  46551. break;
  46552. case Animation.ANIMATIONTYPE_QUATERNION:
  46553. case Animation.ANIMATIONTYPE_MATRIX:
  46554. case Animation.ANIMATIONTYPE_VECTOR3:
  46555. case Animation.ANIMATIONTYPE_COLOR3:
  46556. key.values = animationKey.value.asArray();
  46557. break;
  46558. }
  46559. serializationObject.keys.push(key);
  46560. }
  46561. serializationObject.ranges = [];
  46562. for (var name in this._ranges) {
  46563. var source = this._ranges[name];
  46564. if (!source) {
  46565. continue;
  46566. }
  46567. var range = {};
  46568. range.name = name;
  46569. range.from = source.from;
  46570. range.to = source.to;
  46571. serializationObject.ranges.push(range);
  46572. }
  46573. return serializationObject;
  46574. };
  46575. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46576. get: function () {
  46577. return Animation._ANIMATIONTYPE_FLOAT;
  46578. },
  46579. enumerable: true,
  46580. configurable: true
  46581. });
  46582. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46583. get: function () {
  46584. return Animation._ANIMATIONTYPE_VECTOR3;
  46585. },
  46586. enumerable: true,
  46587. configurable: true
  46588. });
  46589. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46590. get: function () {
  46591. return Animation._ANIMATIONTYPE_VECTOR2;
  46592. },
  46593. enumerable: true,
  46594. configurable: true
  46595. });
  46596. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46597. get: function () {
  46598. return Animation._ANIMATIONTYPE_SIZE;
  46599. },
  46600. enumerable: true,
  46601. configurable: true
  46602. });
  46603. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46604. get: function () {
  46605. return Animation._ANIMATIONTYPE_QUATERNION;
  46606. },
  46607. enumerable: true,
  46608. configurable: true
  46609. });
  46610. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46611. get: function () {
  46612. return Animation._ANIMATIONTYPE_MATRIX;
  46613. },
  46614. enumerable: true,
  46615. configurable: true
  46616. });
  46617. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46618. get: function () {
  46619. return Animation._ANIMATIONTYPE_COLOR3;
  46620. },
  46621. enumerable: true,
  46622. configurable: true
  46623. });
  46624. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46625. get: function () {
  46626. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46627. },
  46628. enumerable: true,
  46629. configurable: true
  46630. });
  46631. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46632. get: function () {
  46633. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46634. },
  46635. enumerable: true,
  46636. configurable: true
  46637. });
  46638. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46639. get: function () {
  46640. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46641. },
  46642. enumerable: true,
  46643. configurable: true
  46644. });
  46645. Animation.Parse = function (parsedAnimation) {
  46646. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46647. var dataType = parsedAnimation.dataType;
  46648. var keys = [];
  46649. var data;
  46650. var index;
  46651. if (parsedAnimation.enableBlending) {
  46652. animation.enableBlending = parsedAnimation.enableBlending;
  46653. }
  46654. if (parsedAnimation.blendingSpeed) {
  46655. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46656. }
  46657. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46658. var key = parsedAnimation.keys[index];
  46659. var inTangent;
  46660. var outTangent;
  46661. switch (dataType) {
  46662. case Animation.ANIMATIONTYPE_FLOAT:
  46663. data = key.values[0];
  46664. if (key.values.length >= 1) {
  46665. inTangent = key.values[1];
  46666. }
  46667. if (key.values.length >= 2) {
  46668. outTangent = key.values[2];
  46669. }
  46670. break;
  46671. case Animation.ANIMATIONTYPE_QUATERNION:
  46672. data = BABYLON.Quaternion.FromArray(key.values);
  46673. if (key.values.length >= 8) {
  46674. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46675. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46676. inTangent = _inTangent;
  46677. }
  46678. }
  46679. if (key.values.length >= 12) {
  46680. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46681. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46682. outTangent = _outTangent;
  46683. }
  46684. }
  46685. break;
  46686. case Animation.ANIMATIONTYPE_MATRIX:
  46687. data = BABYLON.Matrix.FromArray(key.values);
  46688. break;
  46689. case Animation.ANIMATIONTYPE_COLOR3:
  46690. data = BABYLON.Color3.FromArray(key.values);
  46691. break;
  46692. case Animation.ANIMATIONTYPE_VECTOR3:
  46693. default:
  46694. data = BABYLON.Vector3.FromArray(key.values);
  46695. break;
  46696. }
  46697. var keyData = {};
  46698. keyData.frame = key.frame;
  46699. keyData.value = data;
  46700. if (inTangent != undefined) {
  46701. keyData.inTangent = inTangent;
  46702. }
  46703. if (outTangent != undefined) {
  46704. keyData.outTangent = outTangent;
  46705. }
  46706. keys.push(keyData);
  46707. }
  46708. animation.setKeys(keys);
  46709. if (parsedAnimation.ranges) {
  46710. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46711. data = parsedAnimation.ranges[index];
  46712. animation.createRange(data.name, data.from, data.to);
  46713. }
  46714. }
  46715. return animation;
  46716. };
  46717. Animation.AppendSerializedAnimations = function (source, destination) {
  46718. if (source.animations) {
  46719. destination.animations = [];
  46720. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46721. var animation = source.animations[animationIndex];
  46722. destination.animations.push(animation.serialize());
  46723. }
  46724. }
  46725. };
  46726. Animation.AllowMatricesInterpolation = false;
  46727. // Statics
  46728. Animation._ANIMATIONTYPE_FLOAT = 0;
  46729. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46730. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46731. Animation._ANIMATIONTYPE_MATRIX = 3;
  46732. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46733. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46734. Animation._ANIMATIONTYPE_SIZE = 6;
  46735. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46736. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46737. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46738. return Animation;
  46739. }());
  46740. BABYLON.Animation = Animation;
  46741. })(BABYLON || (BABYLON = {}));
  46742. //# sourceMappingURL=babylon.animation.js.map
  46743. var BABYLON;
  46744. (function (BABYLON) {
  46745. /**
  46746. * This class defines the direct association between an animation and a target
  46747. */
  46748. var TargetedAnimation = /** @class */ (function () {
  46749. function TargetedAnimation() {
  46750. }
  46751. return TargetedAnimation;
  46752. }());
  46753. BABYLON.TargetedAnimation = TargetedAnimation;
  46754. /**
  46755. * Use this class to create coordinated animations on multiple targets
  46756. */
  46757. var AnimationGroup = /** @class */ (function () {
  46758. function AnimationGroup(name, scene) {
  46759. if (scene === void 0) { scene = null; }
  46760. this.name = name;
  46761. this._targetedAnimations = new Array();
  46762. this._animatables = new Array();
  46763. this._from = Number.MAX_VALUE;
  46764. this._to = -Number.MAX_VALUE;
  46765. this._speedRatio = 1;
  46766. this.onAnimationEndObservable = new BABYLON.Observable();
  46767. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46768. this._scene.animationGroups.push(this);
  46769. }
  46770. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46771. /**
  46772. * Define if the animations are started
  46773. */
  46774. get: function () {
  46775. return this._isStarted;
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46781. /**
  46782. * Gets or sets the speed ratio to use for all animations
  46783. */
  46784. get: function () {
  46785. return this._speedRatio;
  46786. },
  46787. /**
  46788. * Gets or sets the speed ratio to use for all animations
  46789. */
  46790. set: function (value) {
  46791. if (this._speedRatio === value) {
  46792. return;
  46793. }
  46794. this._speedRatio = value;
  46795. for (var index = 0; index < this._animatables.length; index++) {
  46796. var animatable = this._animatables[index];
  46797. animatable.speedRatio = this._speedRatio;
  46798. }
  46799. },
  46800. enumerable: true,
  46801. configurable: true
  46802. });
  46803. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46804. /**
  46805. * Gets the targeted animations for this animation group
  46806. */
  46807. get: function () {
  46808. return this._targetedAnimations;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. /**
  46814. * Add an animation (with its target) in the group
  46815. * @param animation defines the animation we want to add
  46816. * @param target defines the target of the animation
  46817. * @returns the {BABYLON.TargetedAnimation} object
  46818. */
  46819. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46820. var targetedAnimation = {
  46821. animation: animation,
  46822. target: target
  46823. };
  46824. var keys = animation.getKeys();
  46825. if (this._from > keys[0].frame) {
  46826. this._from = keys[0].frame;
  46827. }
  46828. if (this._to < keys[keys.length - 1].frame) {
  46829. this._to = keys[keys.length - 1].frame;
  46830. }
  46831. this._targetedAnimations.push(targetedAnimation);
  46832. return targetedAnimation;
  46833. };
  46834. /**
  46835. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46836. * It can add constant keys at begin or end
  46837. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46838. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46839. */
  46840. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46841. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46842. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46843. beginFrame = Math.max(beginFrame, this._from);
  46844. endFrame = Math.min(endFrame, this._to);
  46845. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46846. var targetedAnimation = this._targetedAnimations[index];
  46847. var keys = targetedAnimation.animation.getKeys();
  46848. var startKey = keys[0];
  46849. var endKey = keys[keys.length - 1];
  46850. if (startKey.frame > beginFrame) {
  46851. var newKey = {
  46852. frame: beginFrame,
  46853. value: startKey.value,
  46854. inTangent: startKey.inTangent,
  46855. outTangent: startKey.outTangent,
  46856. interpolation: startKey.interpolation
  46857. };
  46858. keys.splice(0, 0, newKey);
  46859. }
  46860. if (endKey.frame < endFrame) {
  46861. var newKey = {
  46862. frame: endFrame,
  46863. value: endKey.value,
  46864. inTangent: endKey.outTangent,
  46865. outTangent: endKey.outTangent,
  46866. interpolation: endKey.interpolation
  46867. };
  46868. keys.push(newKey);
  46869. }
  46870. }
  46871. return this;
  46872. };
  46873. /**
  46874. * Start all animations on given targets
  46875. * @param loop defines if animations must loop
  46876. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46877. */
  46878. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46879. var _this = this;
  46880. if (loop === void 0) { loop = false; }
  46881. if (speedRatio === void 0) { speedRatio = 1; }
  46882. if (this._isStarted || this._targetedAnimations.length === 0) {
  46883. return this;
  46884. }
  46885. var _loop_1 = function () {
  46886. var targetedAnimation = this_1._targetedAnimations[index];
  46887. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46888. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46889. }));
  46890. };
  46891. var this_1 = this;
  46892. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46893. _loop_1();
  46894. }
  46895. this._speedRatio = speedRatio;
  46896. this._isStarted = true;
  46897. return this;
  46898. };
  46899. /**
  46900. * Pause all animations
  46901. */
  46902. AnimationGroup.prototype.pause = function () {
  46903. if (!this._isStarted) {
  46904. return this;
  46905. }
  46906. for (var index = 0; index < this._animatables.length; index++) {
  46907. var animatable = this._animatables[index];
  46908. animatable.pause();
  46909. }
  46910. return this;
  46911. };
  46912. /**
  46913. * Play all animations to initial state
  46914. * This function will start() the animations if they were not started or will restart() them if they were paused
  46915. * @param loop defines if animations must loop
  46916. */
  46917. AnimationGroup.prototype.play = function (loop) {
  46918. if (this.isStarted) {
  46919. if (loop !== undefined) {
  46920. for (var index = 0; index < this._animatables.length; index++) {
  46921. var animatable = this._animatables[index];
  46922. animatable.loopAnimation = loop;
  46923. }
  46924. }
  46925. this.restart();
  46926. }
  46927. else {
  46928. this.start(loop, this._speedRatio);
  46929. }
  46930. return this;
  46931. };
  46932. /**
  46933. * Reset all animations to initial state
  46934. */
  46935. AnimationGroup.prototype.reset = function () {
  46936. if (!this._isStarted) {
  46937. return this;
  46938. }
  46939. for (var index = 0; index < this._animatables.length; index++) {
  46940. var animatable = this._animatables[index];
  46941. animatable.reset();
  46942. }
  46943. return this;
  46944. };
  46945. /**
  46946. * Restart animations from key 0
  46947. */
  46948. AnimationGroup.prototype.restart = function () {
  46949. if (!this._isStarted) {
  46950. return this;
  46951. }
  46952. for (var index = 0; index < this._animatables.length; index++) {
  46953. var animatable = this._animatables[index];
  46954. animatable.restart();
  46955. }
  46956. return this;
  46957. };
  46958. /**
  46959. * Stop all animations
  46960. */
  46961. AnimationGroup.prototype.stop = function () {
  46962. if (!this._isStarted) {
  46963. return this;
  46964. }
  46965. for (var index = 0; index < this._animatables.length; index++) {
  46966. var animatable = this._animatables[index];
  46967. animatable.stop();
  46968. }
  46969. this._isStarted = false;
  46970. return this;
  46971. };
  46972. /**
  46973. * Dispose all associated resources
  46974. */
  46975. AnimationGroup.prototype.dispose = function () {
  46976. this._targetedAnimations = [];
  46977. this._animatables = [];
  46978. var index = this._scene.animationGroups.indexOf(this);
  46979. if (index > -1) {
  46980. this._scene.animationGroups.splice(index, 1);
  46981. }
  46982. };
  46983. return AnimationGroup;
  46984. }());
  46985. BABYLON.AnimationGroup = AnimationGroup;
  46986. })(BABYLON || (BABYLON = {}));
  46987. //# sourceMappingURL=babylon.animationGroup.js.map
  46988. var BABYLON;
  46989. (function (BABYLON) {
  46990. var RuntimeAnimation = /** @class */ (function () {
  46991. function RuntimeAnimation(target, animation) {
  46992. this._offsetsCache = {};
  46993. this._highLimitsCache = {};
  46994. this._stopped = false;
  46995. this._blendingFactor = 0;
  46996. this._ratioOffset = 0;
  46997. this._animation = animation;
  46998. this._target = target;
  46999. animation._runtimeAnimations.push(this);
  47000. }
  47001. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47002. get: function () {
  47003. return this._animation;
  47004. },
  47005. enumerable: true,
  47006. configurable: true
  47007. });
  47008. RuntimeAnimation.prototype.reset = function () {
  47009. this._offsetsCache = {};
  47010. this._highLimitsCache = {};
  47011. this.currentFrame = 0;
  47012. this._blendingFactor = 0;
  47013. this._originalBlendValue = null;
  47014. };
  47015. RuntimeAnimation.prototype.isStopped = function () {
  47016. return this._stopped;
  47017. };
  47018. RuntimeAnimation.prototype.dispose = function () {
  47019. var index = this._animation.runtimeAnimations.indexOf(this);
  47020. if (index > -1) {
  47021. this._animation.runtimeAnimations.splice(index, 1);
  47022. }
  47023. };
  47024. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47025. if (typeof value === "function") {
  47026. return value();
  47027. }
  47028. return value;
  47029. };
  47030. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47031. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47032. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47033. }
  47034. this.currentFrame = currentFrame;
  47035. var keys = this._animation.getKeys();
  47036. // Try to get a hash to find the right key
  47037. 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));
  47038. if (keys[startKeyIndex].frame >= currentFrame) {
  47039. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47040. startKeyIndex--;
  47041. }
  47042. }
  47043. for (var key = startKeyIndex; key < keys.length; key++) {
  47044. var endKey = keys[key + 1];
  47045. if (endKey.frame >= currentFrame) {
  47046. var startKey = keys[key];
  47047. var startValue = this._getKeyValue(startKey.value);
  47048. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47049. return startValue;
  47050. }
  47051. var endValue = this._getKeyValue(endKey.value);
  47052. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47053. var frameDelta = endKey.frame - startKey.frame;
  47054. // gradient : percent of currentFrame between the frame inf and the frame sup
  47055. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47056. // check for easingFunction and correction of gradient
  47057. var easingFunction = this._animation.getEasingFunction();
  47058. if (easingFunction != null) {
  47059. gradient = easingFunction.ease(gradient);
  47060. }
  47061. switch (this._animation.dataType) {
  47062. // Float
  47063. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47064. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47065. switch (loopMode) {
  47066. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47067. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47068. return floatValue;
  47069. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47070. return offsetValue * repeatCount + floatValue;
  47071. }
  47072. break;
  47073. // Quaternion
  47074. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47075. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47076. switch (loopMode) {
  47077. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47078. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47079. return quatValue;
  47080. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47081. return quatValue.add(offsetValue.scale(repeatCount));
  47082. }
  47083. return quatValue;
  47084. // Vector3
  47085. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47086. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47087. switch (loopMode) {
  47088. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47089. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47090. return vec3Value;
  47091. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47092. return vec3Value.add(offsetValue.scale(repeatCount));
  47093. }
  47094. // Vector2
  47095. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47096. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47097. switch (loopMode) {
  47098. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47099. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47100. return vec2Value;
  47101. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47102. return vec2Value.add(offsetValue.scale(repeatCount));
  47103. }
  47104. // Size
  47105. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47106. switch (loopMode) {
  47107. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47108. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47109. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47110. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47111. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47112. }
  47113. // Color3
  47114. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47115. switch (loopMode) {
  47116. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47117. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47118. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47119. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47120. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47121. }
  47122. // Matrix
  47123. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47124. switch (loopMode) {
  47125. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47126. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47127. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47128. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47129. }
  47130. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47131. return startValue;
  47132. }
  47133. default:
  47134. break;
  47135. }
  47136. break;
  47137. }
  47138. }
  47139. return this._getKeyValue(keys[keys.length - 1].value);
  47140. };
  47141. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47142. if (blend === void 0) { blend = false; }
  47143. // Set value
  47144. var path;
  47145. var destination;
  47146. var targetPropertyPath = this._animation.targetPropertyPath;
  47147. if (targetPropertyPath.length > 1) {
  47148. var property = this._target[targetPropertyPath[0]];
  47149. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47150. property = property[targetPropertyPath[index]];
  47151. }
  47152. path = targetPropertyPath[targetPropertyPath.length - 1];
  47153. destination = property;
  47154. }
  47155. else {
  47156. path = targetPropertyPath[0];
  47157. destination = this._target;
  47158. }
  47159. // Blending
  47160. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47161. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47162. if (enableBlending && this._blendingFactor <= 1.0) {
  47163. if (!this._originalBlendValue) {
  47164. if (destination[path].clone) {
  47165. this._originalBlendValue = destination[path].clone();
  47166. }
  47167. else {
  47168. this._originalBlendValue = destination[path];
  47169. }
  47170. }
  47171. if (this._originalBlendValue.prototype) {
  47172. if (this._originalBlendValue.prototype.Lerp) {
  47173. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47174. }
  47175. else {
  47176. destination[path] = currentValue;
  47177. }
  47178. }
  47179. else if (this._originalBlendValue.m) {
  47180. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47181. }
  47182. else {
  47183. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47184. }
  47185. this._blendingFactor += blendingSpeed;
  47186. }
  47187. else {
  47188. destination[path] = currentValue;
  47189. }
  47190. if (this._target.markAsDirty) {
  47191. this._target.markAsDirty(this._animation.targetProperty);
  47192. }
  47193. };
  47194. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47195. if (this._target && this._target.animationPropertiesOverride) {
  47196. return this._target.animationPropertiesOverride.loopMode;
  47197. }
  47198. return this._animation.loopMode;
  47199. };
  47200. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47201. var keys = this._animation.getKeys();
  47202. if (frame < keys[0].frame) {
  47203. frame = keys[0].frame;
  47204. }
  47205. else if (frame > keys[keys.length - 1].frame) {
  47206. frame = keys[keys.length - 1].frame;
  47207. }
  47208. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47209. this.setValue(currentValue);
  47210. };
  47211. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47212. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47213. this._ratioOffset = this._previousRatio - newRatio;
  47214. };
  47215. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47216. if (blend === void 0) { blend = false; }
  47217. var targetPropertyPath = this._animation.targetPropertyPath;
  47218. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47219. this._stopped = true;
  47220. return false;
  47221. }
  47222. var returnValue = true;
  47223. var keys = this._animation.getKeys();
  47224. // Adding a start key at frame 0 if missing
  47225. if (keys[0].frame !== 0) {
  47226. var newKey = { frame: 0, value: keys[0].value };
  47227. keys.splice(0, 0, newKey);
  47228. }
  47229. // Check limits
  47230. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47231. from = keys[0].frame;
  47232. }
  47233. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47234. to = keys[keys.length - 1].frame;
  47235. }
  47236. //to and from cannot be the same key
  47237. if (from === to) {
  47238. if (from > keys[0].frame) {
  47239. from--;
  47240. }
  47241. else if (to < keys[keys.length - 1].frame) {
  47242. to++;
  47243. }
  47244. }
  47245. // Compute ratio
  47246. var range = to - from;
  47247. var offsetValue;
  47248. // ratio represents the frame delta between from and to
  47249. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47250. var highLimitValue = 0;
  47251. this._previousDelay = delay;
  47252. this._previousRatio = ratio;
  47253. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47254. returnValue = false;
  47255. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47256. }
  47257. else {
  47258. // Get max value if required
  47259. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47260. var keyOffset = to.toString() + from.toString();
  47261. if (!this._offsetsCache[keyOffset]) {
  47262. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47263. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47264. switch (this._animation.dataType) {
  47265. // Float
  47266. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47267. this._offsetsCache[keyOffset] = toValue - fromValue;
  47268. break;
  47269. // Quaternion
  47270. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47271. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47272. break;
  47273. // Vector3
  47274. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47275. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47276. // Vector2
  47277. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47278. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47279. // Size
  47280. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47281. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47282. // Color3
  47283. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47284. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47285. default:
  47286. break;
  47287. }
  47288. this._highLimitsCache[keyOffset] = toValue;
  47289. }
  47290. highLimitValue = this._highLimitsCache[keyOffset];
  47291. offsetValue = this._offsetsCache[keyOffset];
  47292. }
  47293. }
  47294. if (offsetValue === undefined) {
  47295. switch (this._animation.dataType) {
  47296. // Float
  47297. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47298. offsetValue = 0;
  47299. break;
  47300. // Quaternion
  47301. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47302. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47303. break;
  47304. // Vector3
  47305. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47306. offsetValue = BABYLON.Vector3.Zero();
  47307. break;
  47308. // Vector2
  47309. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47310. offsetValue = BABYLON.Vector2.Zero();
  47311. break;
  47312. // Size
  47313. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47314. offsetValue = BABYLON.Size.Zero();
  47315. break;
  47316. // Color3
  47317. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47318. offsetValue = BABYLON.Color3.Black();
  47319. }
  47320. }
  47321. // Compute value
  47322. var repeatCount = (ratio / range) >> 0;
  47323. var currentFrame = returnValue ? from + ratio % range : to;
  47324. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47325. // Set value
  47326. this.setValue(currentValue);
  47327. // Check events
  47328. var events = this._animation.getEvents();
  47329. for (var index = 0; index < events.length; index++) {
  47330. // Make sure current frame has passed event frame and that event frame is within the current range
  47331. // Also, handle both forward and reverse animations
  47332. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47333. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47334. var event = events[index];
  47335. if (!event.isDone) {
  47336. // If event should be done only once, remove it.
  47337. if (event.onlyOnce) {
  47338. events.splice(index, 1);
  47339. index--;
  47340. }
  47341. event.isDone = true;
  47342. event.action();
  47343. } // Don't do anything if the event has already be done.
  47344. }
  47345. else if (events[index].isDone && !events[index].onlyOnce) {
  47346. // reset event, the animation is looping
  47347. events[index].isDone = false;
  47348. }
  47349. }
  47350. if (!returnValue) {
  47351. this._stopped = true;
  47352. }
  47353. return returnValue;
  47354. };
  47355. return RuntimeAnimation;
  47356. }());
  47357. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47358. })(BABYLON || (BABYLON = {}));
  47359. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47360. var BABYLON;
  47361. (function (BABYLON) {
  47362. var Animatable = /** @class */ (function () {
  47363. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47364. if (fromFrame === void 0) { fromFrame = 0; }
  47365. if (toFrame === void 0) { toFrame = 100; }
  47366. if (loopAnimation === void 0) { loopAnimation = false; }
  47367. if (speedRatio === void 0) { speedRatio = 1.0; }
  47368. this.target = target;
  47369. this.fromFrame = fromFrame;
  47370. this.toFrame = toFrame;
  47371. this.loopAnimation = loopAnimation;
  47372. this.onAnimationEnd = onAnimationEnd;
  47373. this._localDelayOffset = null;
  47374. this._pausedDelay = null;
  47375. this._runtimeAnimations = new Array();
  47376. this._paused = false;
  47377. this._speedRatio = 1;
  47378. this.animationStarted = false;
  47379. if (animations) {
  47380. this.appendAnimations(target, animations);
  47381. }
  47382. this._speedRatio = speedRatio;
  47383. this._scene = scene;
  47384. scene._activeAnimatables.push(this);
  47385. }
  47386. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47387. get: function () {
  47388. return this._speedRatio;
  47389. },
  47390. set: function (value) {
  47391. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47392. var animation = this._runtimeAnimations[index];
  47393. animation._prepareForSpeedRatioChange(value);
  47394. }
  47395. this._speedRatio = value;
  47396. },
  47397. enumerable: true,
  47398. configurable: true
  47399. });
  47400. // Methods
  47401. Animatable.prototype.getAnimations = function () {
  47402. return this._runtimeAnimations;
  47403. };
  47404. Animatable.prototype.appendAnimations = function (target, animations) {
  47405. for (var index = 0; index < animations.length; index++) {
  47406. var animation = animations[index];
  47407. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47408. }
  47409. };
  47410. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47411. var runtimeAnimations = this._runtimeAnimations;
  47412. for (var index = 0; index < runtimeAnimations.length; index++) {
  47413. if (runtimeAnimations[index].animation.targetProperty === property) {
  47414. return runtimeAnimations[index].animation;
  47415. }
  47416. }
  47417. return null;
  47418. };
  47419. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47420. var runtimeAnimations = this._runtimeAnimations;
  47421. for (var index = 0; index < runtimeAnimations.length; index++) {
  47422. if (runtimeAnimations[index].animation.targetProperty === property) {
  47423. return runtimeAnimations[index];
  47424. }
  47425. }
  47426. return null;
  47427. };
  47428. Animatable.prototype.reset = function () {
  47429. var runtimeAnimations = this._runtimeAnimations;
  47430. for (var index = 0; index < runtimeAnimations.length; index++) {
  47431. runtimeAnimations[index].reset();
  47432. }
  47433. // Reset to original value
  47434. for (index = 0; index < runtimeAnimations.length; index++) {
  47435. var animation = runtimeAnimations[index];
  47436. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47437. }
  47438. this._localDelayOffset = null;
  47439. this._pausedDelay = null;
  47440. };
  47441. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47442. var runtimeAnimations = this._runtimeAnimations;
  47443. for (var index = 0; index < runtimeAnimations.length; index++) {
  47444. runtimeAnimations[index].animation.enableBlending = true;
  47445. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47446. }
  47447. };
  47448. Animatable.prototype.disableBlending = function () {
  47449. var runtimeAnimations = this._runtimeAnimations;
  47450. for (var index = 0; index < runtimeAnimations.length; index++) {
  47451. runtimeAnimations[index].animation.enableBlending = false;
  47452. }
  47453. };
  47454. Animatable.prototype.goToFrame = function (frame) {
  47455. var runtimeAnimations = this._runtimeAnimations;
  47456. if (runtimeAnimations[0]) {
  47457. var fps = runtimeAnimations[0].animation.framePerSecond;
  47458. var currentFrame = runtimeAnimations[0].currentFrame;
  47459. var adjustTime = frame - currentFrame;
  47460. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47461. if (this._localDelayOffset === null) {
  47462. this._localDelayOffset = 0;
  47463. }
  47464. this._localDelayOffset -= delay;
  47465. }
  47466. for (var index = 0; index < runtimeAnimations.length; index++) {
  47467. runtimeAnimations[index].goToFrame(frame);
  47468. }
  47469. };
  47470. Animatable.prototype.pause = function () {
  47471. if (this._paused) {
  47472. return;
  47473. }
  47474. this._paused = true;
  47475. };
  47476. Animatable.prototype.restart = function () {
  47477. this._paused = false;
  47478. };
  47479. Animatable.prototype.stop = function (animationName) {
  47480. if (animationName) {
  47481. var idx = this._scene._activeAnimatables.indexOf(this);
  47482. if (idx > -1) {
  47483. var runtimeAnimations = this._runtimeAnimations;
  47484. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47485. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47486. continue;
  47487. }
  47488. runtimeAnimations[index].dispose();
  47489. runtimeAnimations.splice(index, 1);
  47490. }
  47491. if (runtimeAnimations.length == 0) {
  47492. this._scene._activeAnimatables.splice(idx, 1);
  47493. if (this.onAnimationEnd) {
  47494. this.onAnimationEnd();
  47495. }
  47496. }
  47497. }
  47498. }
  47499. else {
  47500. var index = this._scene._activeAnimatables.indexOf(this);
  47501. if (index > -1) {
  47502. this._scene._activeAnimatables.splice(index, 1);
  47503. var runtimeAnimations = this._runtimeAnimations;
  47504. for (var index = 0; index < runtimeAnimations.length; index++) {
  47505. runtimeAnimations[index].dispose();
  47506. }
  47507. if (this.onAnimationEnd) {
  47508. this.onAnimationEnd();
  47509. }
  47510. }
  47511. }
  47512. };
  47513. Animatable.prototype._animate = function (delay) {
  47514. if (this._paused) {
  47515. this.animationStarted = false;
  47516. if (this._pausedDelay === null) {
  47517. this._pausedDelay = delay;
  47518. }
  47519. return true;
  47520. }
  47521. if (this._localDelayOffset === null) {
  47522. this._localDelayOffset = delay;
  47523. this._pausedDelay = null;
  47524. }
  47525. else if (this._pausedDelay !== null) {
  47526. this._localDelayOffset += delay - this._pausedDelay;
  47527. this._pausedDelay = null;
  47528. }
  47529. // Animating
  47530. var running = false;
  47531. var runtimeAnimations = this._runtimeAnimations;
  47532. var index;
  47533. for (index = 0; index < runtimeAnimations.length; index++) {
  47534. var animation = runtimeAnimations[index];
  47535. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47536. running = running || isRunning;
  47537. }
  47538. this.animationStarted = running;
  47539. if (!running) {
  47540. // Remove from active animatables
  47541. index = this._scene._activeAnimatables.indexOf(this);
  47542. this._scene._activeAnimatables.splice(index, 1);
  47543. // Dispose all runtime animations
  47544. for (index = 0; index < runtimeAnimations.length; index++) {
  47545. runtimeAnimations[index].dispose();
  47546. }
  47547. }
  47548. if (!running && this.onAnimationEnd) {
  47549. this.onAnimationEnd();
  47550. this.onAnimationEnd = null;
  47551. }
  47552. return running;
  47553. };
  47554. return Animatable;
  47555. }());
  47556. BABYLON.Animatable = Animatable;
  47557. })(BABYLON || (BABYLON = {}));
  47558. //# sourceMappingURL=babylon.animatable.js.map
  47559. var BABYLON;
  47560. (function (BABYLON) {
  47561. var EasingFunction = /** @class */ (function () {
  47562. function EasingFunction() {
  47563. // Properties
  47564. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47565. }
  47566. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47567. get: function () {
  47568. return EasingFunction._EASINGMODE_EASEIN;
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47574. get: function () {
  47575. return EasingFunction._EASINGMODE_EASEOUT;
  47576. },
  47577. enumerable: true,
  47578. configurable: true
  47579. });
  47580. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47581. get: function () {
  47582. return EasingFunction._EASINGMODE_EASEINOUT;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47588. var n = Math.min(Math.max(easingMode, 0), 2);
  47589. this._easingMode = n;
  47590. };
  47591. EasingFunction.prototype.getEasingMode = function () {
  47592. return this._easingMode;
  47593. };
  47594. EasingFunction.prototype.easeInCore = function (gradient) {
  47595. throw new Error('You must implement this method');
  47596. };
  47597. EasingFunction.prototype.ease = function (gradient) {
  47598. switch (this._easingMode) {
  47599. case EasingFunction.EASINGMODE_EASEIN:
  47600. return this.easeInCore(gradient);
  47601. case EasingFunction.EASINGMODE_EASEOUT:
  47602. return (1 - this.easeInCore(1 - gradient));
  47603. }
  47604. if (gradient >= 0.5) {
  47605. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47606. }
  47607. return (this.easeInCore(gradient * 2) * 0.5);
  47608. };
  47609. //Statics
  47610. EasingFunction._EASINGMODE_EASEIN = 0;
  47611. EasingFunction._EASINGMODE_EASEOUT = 1;
  47612. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47613. return EasingFunction;
  47614. }());
  47615. BABYLON.EasingFunction = EasingFunction;
  47616. var CircleEase = /** @class */ (function (_super) {
  47617. __extends(CircleEase, _super);
  47618. function CircleEase() {
  47619. return _super !== null && _super.apply(this, arguments) || this;
  47620. }
  47621. CircleEase.prototype.easeInCore = function (gradient) {
  47622. gradient = Math.max(0, Math.min(1, gradient));
  47623. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47624. };
  47625. return CircleEase;
  47626. }(EasingFunction));
  47627. BABYLON.CircleEase = CircleEase;
  47628. var BackEase = /** @class */ (function (_super) {
  47629. __extends(BackEase, _super);
  47630. function BackEase(amplitude) {
  47631. if (amplitude === void 0) { amplitude = 1; }
  47632. var _this = _super.call(this) || this;
  47633. _this.amplitude = amplitude;
  47634. return _this;
  47635. }
  47636. BackEase.prototype.easeInCore = function (gradient) {
  47637. var num = Math.max(0, this.amplitude);
  47638. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47639. };
  47640. return BackEase;
  47641. }(EasingFunction));
  47642. BABYLON.BackEase = BackEase;
  47643. var BounceEase = /** @class */ (function (_super) {
  47644. __extends(BounceEase, _super);
  47645. function BounceEase(bounces, bounciness) {
  47646. if (bounces === void 0) { bounces = 3; }
  47647. if (bounciness === void 0) { bounciness = 2; }
  47648. var _this = _super.call(this) || this;
  47649. _this.bounces = bounces;
  47650. _this.bounciness = bounciness;
  47651. return _this;
  47652. }
  47653. BounceEase.prototype.easeInCore = function (gradient) {
  47654. var y = Math.max(0.0, this.bounces);
  47655. var bounciness = this.bounciness;
  47656. if (bounciness <= 1.0) {
  47657. bounciness = 1.001;
  47658. }
  47659. var num9 = Math.pow(bounciness, y);
  47660. var num5 = 1.0 - bounciness;
  47661. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47662. var num15 = gradient * num4;
  47663. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47664. var num3 = Math.floor(num65);
  47665. var num13 = num3 + 1.0;
  47666. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47667. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47668. var num7 = (num8 + num12) * 0.5;
  47669. var num6 = gradient - num7;
  47670. var num2 = num7 - num8;
  47671. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47672. };
  47673. return BounceEase;
  47674. }(EasingFunction));
  47675. BABYLON.BounceEase = BounceEase;
  47676. var CubicEase = /** @class */ (function (_super) {
  47677. __extends(CubicEase, _super);
  47678. function CubicEase() {
  47679. return _super !== null && _super.apply(this, arguments) || this;
  47680. }
  47681. CubicEase.prototype.easeInCore = function (gradient) {
  47682. return (gradient * gradient * gradient);
  47683. };
  47684. return CubicEase;
  47685. }(EasingFunction));
  47686. BABYLON.CubicEase = CubicEase;
  47687. var ElasticEase = /** @class */ (function (_super) {
  47688. __extends(ElasticEase, _super);
  47689. function ElasticEase(oscillations, springiness) {
  47690. if (oscillations === void 0) { oscillations = 3; }
  47691. if (springiness === void 0) { springiness = 3; }
  47692. var _this = _super.call(this) || this;
  47693. _this.oscillations = oscillations;
  47694. _this.springiness = springiness;
  47695. return _this;
  47696. }
  47697. ElasticEase.prototype.easeInCore = function (gradient) {
  47698. var num2;
  47699. var num3 = Math.max(0.0, this.oscillations);
  47700. var num = Math.max(0.0, this.springiness);
  47701. if (num == 0) {
  47702. num2 = gradient;
  47703. }
  47704. else {
  47705. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47706. }
  47707. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47708. };
  47709. return ElasticEase;
  47710. }(EasingFunction));
  47711. BABYLON.ElasticEase = ElasticEase;
  47712. var ExponentialEase = /** @class */ (function (_super) {
  47713. __extends(ExponentialEase, _super);
  47714. function ExponentialEase(exponent) {
  47715. if (exponent === void 0) { exponent = 2; }
  47716. var _this = _super.call(this) || this;
  47717. _this.exponent = exponent;
  47718. return _this;
  47719. }
  47720. ExponentialEase.prototype.easeInCore = function (gradient) {
  47721. if (this.exponent <= 0) {
  47722. return gradient;
  47723. }
  47724. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47725. };
  47726. return ExponentialEase;
  47727. }(EasingFunction));
  47728. BABYLON.ExponentialEase = ExponentialEase;
  47729. var PowerEase = /** @class */ (function (_super) {
  47730. __extends(PowerEase, _super);
  47731. function PowerEase(power) {
  47732. if (power === void 0) { power = 2; }
  47733. var _this = _super.call(this) || this;
  47734. _this.power = power;
  47735. return _this;
  47736. }
  47737. PowerEase.prototype.easeInCore = function (gradient) {
  47738. var y = Math.max(0.0, this.power);
  47739. return Math.pow(gradient, y);
  47740. };
  47741. return PowerEase;
  47742. }(EasingFunction));
  47743. BABYLON.PowerEase = PowerEase;
  47744. var QuadraticEase = /** @class */ (function (_super) {
  47745. __extends(QuadraticEase, _super);
  47746. function QuadraticEase() {
  47747. return _super !== null && _super.apply(this, arguments) || this;
  47748. }
  47749. QuadraticEase.prototype.easeInCore = function (gradient) {
  47750. return (gradient * gradient);
  47751. };
  47752. return QuadraticEase;
  47753. }(EasingFunction));
  47754. BABYLON.QuadraticEase = QuadraticEase;
  47755. var QuarticEase = /** @class */ (function (_super) {
  47756. __extends(QuarticEase, _super);
  47757. function QuarticEase() {
  47758. return _super !== null && _super.apply(this, arguments) || this;
  47759. }
  47760. QuarticEase.prototype.easeInCore = function (gradient) {
  47761. return (gradient * gradient * gradient * gradient);
  47762. };
  47763. return QuarticEase;
  47764. }(EasingFunction));
  47765. BABYLON.QuarticEase = QuarticEase;
  47766. var QuinticEase = /** @class */ (function (_super) {
  47767. __extends(QuinticEase, _super);
  47768. function QuinticEase() {
  47769. return _super !== null && _super.apply(this, arguments) || this;
  47770. }
  47771. QuinticEase.prototype.easeInCore = function (gradient) {
  47772. return (gradient * gradient * gradient * gradient * gradient);
  47773. };
  47774. return QuinticEase;
  47775. }(EasingFunction));
  47776. BABYLON.QuinticEase = QuinticEase;
  47777. var SineEase = /** @class */ (function (_super) {
  47778. __extends(SineEase, _super);
  47779. function SineEase() {
  47780. return _super !== null && _super.apply(this, arguments) || this;
  47781. }
  47782. SineEase.prototype.easeInCore = function (gradient) {
  47783. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47784. };
  47785. return SineEase;
  47786. }(EasingFunction));
  47787. BABYLON.SineEase = SineEase;
  47788. var BezierCurveEase = /** @class */ (function (_super) {
  47789. __extends(BezierCurveEase, _super);
  47790. function BezierCurveEase(x1, y1, x2, y2) {
  47791. if (x1 === void 0) { x1 = 0; }
  47792. if (y1 === void 0) { y1 = 0; }
  47793. if (x2 === void 0) { x2 = 1; }
  47794. if (y2 === void 0) { y2 = 1; }
  47795. var _this = _super.call(this) || this;
  47796. _this.x1 = x1;
  47797. _this.y1 = y1;
  47798. _this.x2 = x2;
  47799. _this.y2 = y2;
  47800. return _this;
  47801. }
  47802. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47803. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47804. };
  47805. return BezierCurveEase;
  47806. }(EasingFunction));
  47807. BABYLON.BezierCurveEase = BezierCurveEase;
  47808. })(BABYLON || (BABYLON = {}));
  47809. //# sourceMappingURL=babylon.easing.js.map
  47810. var BABYLON;
  47811. (function (BABYLON) {
  47812. var Condition = /** @class */ (function () {
  47813. function Condition(actionManager) {
  47814. this._actionManager = actionManager;
  47815. }
  47816. Condition.prototype.isValid = function () {
  47817. return true;
  47818. };
  47819. Condition.prototype._getProperty = function (propertyPath) {
  47820. return this._actionManager._getProperty(propertyPath);
  47821. };
  47822. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47823. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47824. };
  47825. Condition.prototype.serialize = function () {
  47826. };
  47827. Condition.prototype._serialize = function (serializedCondition) {
  47828. return {
  47829. type: 2,
  47830. children: [],
  47831. name: serializedCondition.name,
  47832. properties: serializedCondition.properties
  47833. };
  47834. };
  47835. return Condition;
  47836. }());
  47837. BABYLON.Condition = Condition;
  47838. var ValueCondition = /** @class */ (function (_super) {
  47839. __extends(ValueCondition, _super);
  47840. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47841. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47842. var _this = _super.call(this, actionManager) || this;
  47843. _this.propertyPath = propertyPath;
  47844. _this.value = value;
  47845. _this.operator = operator;
  47846. _this._target = target;
  47847. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47848. _this._property = _this._getProperty(_this.propertyPath);
  47849. return _this;
  47850. }
  47851. Object.defineProperty(ValueCondition, "IsEqual", {
  47852. get: function () {
  47853. return ValueCondition._IsEqual;
  47854. },
  47855. enumerable: true,
  47856. configurable: true
  47857. });
  47858. Object.defineProperty(ValueCondition, "IsDifferent", {
  47859. get: function () {
  47860. return ValueCondition._IsDifferent;
  47861. },
  47862. enumerable: true,
  47863. configurable: true
  47864. });
  47865. Object.defineProperty(ValueCondition, "IsGreater", {
  47866. get: function () {
  47867. return ValueCondition._IsGreater;
  47868. },
  47869. enumerable: true,
  47870. configurable: true
  47871. });
  47872. Object.defineProperty(ValueCondition, "IsLesser", {
  47873. get: function () {
  47874. return ValueCondition._IsLesser;
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. // Methods
  47880. ValueCondition.prototype.isValid = function () {
  47881. switch (this.operator) {
  47882. case ValueCondition.IsGreater:
  47883. return this._effectiveTarget[this._property] > this.value;
  47884. case ValueCondition.IsLesser:
  47885. return this._effectiveTarget[this._property] < this.value;
  47886. case ValueCondition.IsEqual:
  47887. case ValueCondition.IsDifferent:
  47888. var check;
  47889. if (this.value.equals) {
  47890. check = this.value.equals(this._effectiveTarget[this._property]);
  47891. }
  47892. else {
  47893. check = this.value === this._effectiveTarget[this._property];
  47894. }
  47895. return this.operator === ValueCondition.IsEqual ? check : !check;
  47896. }
  47897. return false;
  47898. };
  47899. ValueCondition.prototype.serialize = function () {
  47900. return this._serialize({
  47901. name: "ValueCondition",
  47902. properties: [
  47903. BABYLON.Action._GetTargetProperty(this._target),
  47904. { name: "propertyPath", value: this.propertyPath },
  47905. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47906. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47907. ]
  47908. });
  47909. };
  47910. ValueCondition.GetOperatorName = function (operator) {
  47911. switch (operator) {
  47912. case ValueCondition._IsEqual: return "IsEqual";
  47913. case ValueCondition._IsDifferent: return "IsDifferent";
  47914. case ValueCondition._IsGreater: return "IsGreater";
  47915. case ValueCondition._IsLesser: return "IsLesser";
  47916. default: return "";
  47917. }
  47918. };
  47919. // Statics
  47920. ValueCondition._IsEqual = 0;
  47921. ValueCondition._IsDifferent = 1;
  47922. ValueCondition._IsGreater = 2;
  47923. ValueCondition._IsLesser = 3;
  47924. return ValueCondition;
  47925. }(Condition));
  47926. BABYLON.ValueCondition = ValueCondition;
  47927. var PredicateCondition = /** @class */ (function (_super) {
  47928. __extends(PredicateCondition, _super);
  47929. function PredicateCondition(actionManager, predicate) {
  47930. var _this = _super.call(this, actionManager) || this;
  47931. _this.predicate = predicate;
  47932. return _this;
  47933. }
  47934. PredicateCondition.prototype.isValid = function () {
  47935. return this.predicate();
  47936. };
  47937. return PredicateCondition;
  47938. }(Condition));
  47939. BABYLON.PredicateCondition = PredicateCondition;
  47940. var StateCondition = /** @class */ (function (_super) {
  47941. __extends(StateCondition, _super);
  47942. function StateCondition(actionManager, target, value) {
  47943. var _this = _super.call(this, actionManager) || this;
  47944. _this.value = value;
  47945. _this._target = target;
  47946. return _this;
  47947. }
  47948. // Methods
  47949. StateCondition.prototype.isValid = function () {
  47950. return this._target.state === this.value;
  47951. };
  47952. StateCondition.prototype.serialize = function () {
  47953. return this._serialize({
  47954. name: "StateCondition",
  47955. properties: [
  47956. BABYLON.Action._GetTargetProperty(this._target),
  47957. { name: "value", value: this.value }
  47958. ]
  47959. });
  47960. };
  47961. return StateCondition;
  47962. }(Condition));
  47963. BABYLON.StateCondition = StateCondition;
  47964. })(BABYLON || (BABYLON = {}));
  47965. //# sourceMappingURL=babylon.condition.js.map
  47966. var BABYLON;
  47967. (function (BABYLON) {
  47968. var Action = /** @class */ (function () {
  47969. function Action(triggerOptions, condition) {
  47970. this.triggerOptions = triggerOptions;
  47971. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47972. if (triggerOptions.parameter) {
  47973. this.trigger = triggerOptions.trigger;
  47974. this._triggerParameter = triggerOptions.parameter;
  47975. }
  47976. else {
  47977. this.trigger = triggerOptions;
  47978. }
  47979. this._nextActiveAction = this;
  47980. this._condition = condition;
  47981. }
  47982. // Methods
  47983. Action.prototype._prepare = function () {
  47984. };
  47985. Action.prototype.getTriggerParameter = function () {
  47986. return this._triggerParameter;
  47987. };
  47988. Action.prototype._executeCurrent = function (evt) {
  47989. if (this._nextActiveAction._condition) {
  47990. var condition = this._nextActiveAction._condition;
  47991. var currentRenderId = this._actionManager.getScene().getRenderId();
  47992. // We cache the current evaluation for the current frame
  47993. if (condition._evaluationId === currentRenderId) {
  47994. if (!condition._currentResult) {
  47995. return;
  47996. }
  47997. }
  47998. else {
  47999. condition._evaluationId = currentRenderId;
  48000. if (!condition.isValid()) {
  48001. condition._currentResult = false;
  48002. return;
  48003. }
  48004. condition._currentResult = true;
  48005. }
  48006. }
  48007. this.onBeforeExecuteObservable.notifyObservers(this);
  48008. this._nextActiveAction.execute(evt);
  48009. this.skipToNextActiveAction();
  48010. };
  48011. Action.prototype.execute = function (evt) {
  48012. };
  48013. Action.prototype.skipToNextActiveAction = function () {
  48014. if (this._nextActiveAction._child) {
  48015. if (!this._nextActiveAction._child._actionManager) {
  48016. this._nextActiveAction._child._actionManager = this._actionManager;
  48017. }
  48018. this._nextActiveAction = this._nextActiveAction._child;
  48019. }
  48020. else {
  48021. this._nextActiveAction = this;
  48022. }
  48023. };
  48024. Action.prototype.then = function (action) {
  48025. this._child = action;
  48026. action._actionManager = this._actionManager;
  48027. action._prepare();
  48028. return action;
  48029. };
  48030. Action.prototype._getProperty = function (propertyPath) {
  48031. return this._actionManager._getProperty(propertyPath);
  48032. };
  48033. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48034. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48035. };
  48036. Action.prototype.serialize = function (parent) {
  48037. };
  48038. // Called by BABYLON.Action objects in serialize(...). Internal use
  48039. Action.prototype._serialize = function (serializedAction, parent) {
  48040. var serializationObject = {
  48041. type: 1,
  48042. children: [],
  48043. name: serializedAction.name,
  48044. properties: serializedAction.properties || []
  48045. };
  48046. // Serialize child
  48047. if (this._child) {
  48048. this._child.serialize(serializationObject);
  48049. }
  48050. // Check if "this" has a condition
  48051. if (this._condition) {
  48052. var serializedCondition = this._condition.serialize();
  48053. serializedCondition.children.push(serializationObject);
  48054. if (parent) {
  48055. parent.children.push(serializedCondition);
  48056. }
  48057. return serializedCondition;
  48058. }
  48059. if (parent) {
  48060. parent.children.push(serializationObject);
  48061. }
  48062. return serializationObject;
  48063. };
  48064. Action._SerializeValueAsString = function (value) {
  48065. if (typeof value === "number") {
  48066. return value.toString();
  48067. }
  48068. if (typeof value === "boolean") {
  48069. return value ? "true" : "false";
  48070. }
  48071. if (value instanceof BABYLON.Vector2) {
  48072. return value.x + ", " + value.y;
  48073. }
  48074. if (value instanceof BABYLON.Vector3) {
  48075. return value.x + ", " + value.y + ", " + value.z;
  48076. }
  48077. if (value instanceof BABYLON.Color3) {
  48078. return value.r + ", " + value.g + ", " + value.b;
  48079. }
  48080. if (value instanceof BABYLON.Color4) {
  48081. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48082. }
  48083. return value; // string
  48084. };
  48085. Action._GetTargetProperty = function (target) {
  48086. return {
  48087. name: "target",
  48088. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48089. : target instanceof BABYLON.Light ? "LightProperties"
  48090. : target instanceof BABYLON.Camera ? "CameraProperties"
  48091. : "SceneProperties",
  48092. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48093. };
  48094. };
  48095. return Action;
  48096. }());
  48097. BABYLON.Action = Action;
  48098. })(BABYLON || (BABYLON = {}));
  48099. //# sourceMappingURL=babylon.action.js.map
  48100. var BABYLON;
  48101. (function (BABYLON) {
  48102. /**
  48103. * ActionEvent is the event beint sent when an action is triggered.
  48104. */
  48105. var ActionEvent = /** @class */ (function () {
  48106. /**
  48107. * @param source The mesh or sprite that triggered the action.
  48108. * @param pointerX The X mouse cursor position at the time of the event
  48109. * @param pointerY The Y mouse cursor position at the time of the event
  48110. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48111. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48112. */
  48113. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48114. this.source = source;
  48115. this.pointerX = pointerX;
  48116. this.pointerY = pointerY;
  48117. this.meshUnderPointer = meshUnderPointer;
  48118. this.sourceEvent = sourceEvent;
  48119. this.additionalData = additionalData;
  48120. }
  48121. /**
  48122. * Helper function to auto-create an ActionEvent from a source mesh.
  48123. * @param source The source mesh that triggered the event
  48124. * @param evt {Event} The original (browser) event
  48125. */
  48126. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48127. var scene = source.getScene();
  48128. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48129. };
  48130. /**
  48131. * Helper function to auto-create an ActionEvent from a source mesh.
  48132. * @param source The source sprite that triggered the event
  48133. * @param scene Scene associated with the sprite
  48134. * @param evt {Event} The original (browser) event
  48135. */
  48136. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48137. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48138. };
  48139. /**
  48140. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48141. * @param scene the scene where the event occurred
  48142. * @param evt {Event} The original (browser) event
  48143. */
  48144. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48145. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48146. };
  48147. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48148. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48149. };
  48150. return ActionEvent;
  48151. }());
  48152. BABYLON.ActionEvent = ActionEvent;
  48153. /**
  48154. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48155. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48156. */
  48157. var ActionManager = /** @class */ (function () {
  48158. function ActionManager(scene) {
  48159. // Members
  48160. this.actions = new Array();
  48161. this.hoverCursor = '';
  48162. this._scene = scene;
  48163. scene._actionManagers.push(this);
  48164. }
  48165. Object.defineProperty(ActionManager, "NothingTrigger", {
  48166. get: function () {
  48167. return ActionManager._NothingTrigger;
  48168. },
  48169. enumerable: true,
  48170. configurable: true
  48171. });
  48172. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48173. get: function () {
  48174. return ActionManager._OnPickTrigger;
  48175. },
  48176. enumerable: true,
  48177. configurable: true
  48178. });
  48179. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48180. get: function () {
  48181. return ActionManager._OnLeftPickTrigger;
  48182. },
  48183. enumerable: true,
  48184. configurable: true
  48185. });
  48186. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48187. get: function () {
  48188. return ActionManager._OnRightPickTrigger;
  48189. },
  48190. enumerable: true,
  48191. configurable: true
  48192. });
  48193. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48194. get: function () {
  48195. return ActionManager._OnCenterPickTrigger;
  48196. },
  48197. enumerable: true,
  48198. configurable: true
  48199. });
  48200. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48201. get: function () {
  48202. return ActionManager._OnPickDownTrigger;
  48203. },
  48204. enumerable: true,
  48205. configurable: true
  48206. });
  48207. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48208. get: function () {
  48209. return ActionManager._OnDoublePickTrigger;
  48210. },
  48211. enumerable: true,
  48212. configurable: true
  48213. });
  48214. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48215. get: function () {
  48216. return ActionManager._OnPickUpTrigger;
  48217. },
  48218. enumerable: true,
  48219. configurable: true
  48220. });
  48221. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48222. /// This trigger will only be raised if you also declared a OnPickDown
  48223. get: function () {
  48224. return ActionManager._OnPickOutTrigger;
  48225. },
  48226. enumerable: true,
  48227. configurable: true
  48228. });
  48229. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48230. get: function () {
  48231. return ActionManager._OnLongPressTrigger;
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48237. get: function () {
  48238. return ActionManager._OnPointerOverTrigger;
  48239. },
  48240. enumerable: true,
  48241. configurable: true
  48242. });
  48243. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48244. get: function () {
  48245. return ActionManager._OnPointerOutTrigger;
  48246. },
  48247. enumerable: true,
  48248. configurable: true
  48249. });
  48250. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48251. get: function () {
  48252. return ActionManager._OnEveryFrameTrigger;
  48253. },
  48254. enumerable: true,
  48255. configurable: true
  48256. });
  48257. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48258. get: function () {
  48259. return ActionManager._OnIntersectionEnterTrigger;
  48260. },
  48261. enumerable: true,
  48262. configurable: true
  48263. });
  48264. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48265. get: function () {
  48266. return ActionManager._OnIntersectionExitTrigger;
  48267. },
  48268. enumerable: true,
  48269. configurable: true
  48270. });
  48271. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48272. get: function () {
  48273. return ActionManager._OnKeyDownTrigger;
  48274. },
  48275. enumerable: true,
  48276. configurable: true
  48277. });
  48278. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48279. get: function () {
  48280. return ActionManager._OnKeyUpTrigger;
  48281. },
  48282. enumerable: true,
  48283. configurable: true
  48284. });
  48285. // Methods
  48286. ActionManager.prototype.dispose = function () {
  48287. var index = this._scene._actionManagers.indexOf(this);
  48288. for (var i = 0; i < this.actions.length; i++) {
  48289. var action = this.actions[i];
  48290. ActionManager.Triggers[action.trigger]--;
  48291. if (ActionManager.Triggers[action.trigger] === 0) {
  48292. delete ActionManager.Triggers[action.trigger];
  48293. }
  48294. }
  48295. if (index > -1) {
  48296. this._scene._actionManagers.splice(index, 1);
  48297. }
  48298. };
  48299. ActionManager.prototype.getScene = function () {
  48300. return this._scene;
  48301. };
  48302. /**
  48303. * Does this action manager handles actions of any of the given triggers
  48304. * @param {number[]} triggers - the triggers to be tested
  48305. * @return {boolean} whether one (or more) of the triggers is handeled
  48306. */
  48307. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48308. for (var index = 0; index < this.actions.length; index++) {
  48309. var action = this.actions[index];
  48310. if (triggers.indexOf(action.trigger) > -1) {
  48311. return true;
  48312. }
  48313. }
  48314. return false;
  48315. };
  48316. /**
  48317. * Does this action manager handles actions of a given trigger
  48318. * @param {number} trigger - the trigger to be tested
  48319. * @return {boolean} whether the trigger is handeled
  48320. */
  48321. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48322. for (var index = 0; index < this.actions.length; index++) {
  48323. var action = this.actions[index];
  48324. if (action.trigger === trigger) {
  48325. return true;
  48326. }
  48327. }
  48328. return false;
  48329. };
  48330. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48331. /**
  48332. * Does this action manager has pointer triggers
  48333. * @return {boolean} whether or not it has pointer triggers
  48334. */
  48335. get: function () {
  48336. for (var index = 0; index < this.actions.length; index++) {
  48337. var action = this.actions[index];
  48338. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48339. return true;
  48340. }
  48341. }
  48342. return false;
  48343. },
  48344. enumerable: true,
  48345. configurable: true
  48346. });
  48347. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48348. /**
  48349. * Does this action manager has pick triggers
  48350. * @return {boolean} whether or not it has pick triggers
  48351. */
  48352. get: function () {
  48353. for (var index = 0; index < this.actions.length; index++) {
  48354. var action = this.actions[index];
  48355. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48356. return true;
  48357. }
  48358. }
  48359. return false;
  48360. },
  48361. enumerable: true,
  48362. configurable: true
  48363. });
  48364. Object.defineProperty(ActionManager, "HasTriggers", {
  48365. /**
  48366. * Does exist one action manager with at least one trigger
  48367. * @return {boolean} whether or not it exists one action manager with one trigger
  48368. **/
  48369. get: function () {
  48370. for (var t in ActionManager.Triggers) {
  48371. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48372. return true;
  48373. }
  48374. }
  48375. return false;
  48376. },
  48377. enumerable: true,
  48378. configurable: true
  48379. });
  48380. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48381. /**
  48382. * Does exist one action manager with at least one pick trigger
  48383. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48384. **/
  48385. get: function () {
  48386. for (var t in ActionManager.Triggers) {
  48387. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48388. var t_int = parseInt(t);
  48389. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48390. return true;
  48391. }
  48392. }
  48393. }
  48394. return false;
  48395. },
  48396. enumerable: true,
  48397. configurable: true
  48398. });
  48399. /**
  48400. * Does exist one action manager that handles actions of a given trigger
  48401. * @param {number} trigger - the trigger to be tested
  48402. * @return {boolean} whether the trigger is handeled by at least one action manager
  48403. **/
  48404. ActionManager.HasSpecificTrigger = function (trigger) {
  48405. for (var t in ActionManager.Triggers) {
  48406. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48407. var t_int = parseInt(t);
  48408. if (t_int === trigger) {
  48409. return true;
  48410. }
  48411. }
  48412. }
  48413. return false;
  48414. };
  48415. /**
  48416. * Registers an action to this action manager
  48417. * @param {BABYLON.Action} action - the action to be registered
  48418. * @return {BABYLON.Action} the action amended (prepared) after registration
  48419. */
  48420. ActionManager.prototype.registerAction = function (action) {
  48421. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48422. if (this.getScene().actionManager !== this) {
  48423. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48424. return null;
  48425. }
  48426. }
  48427. this.actions.push(action);
  48428. if (ActionManager.Triggers[action.trigger]) {
  48429. ActionManager.Triggers[action.trigger]++;
  48430. }
  48431. else {
  48432. ActionManager.Triggers[action.trigger] = 1;
  48433. }
  48434. action._actionManager = this;
  48435. action._prepare();
  48436. return action;
  48437. };
  48438. /**
  48439. * Unregisters an action to this action manager
  48440. * @param action The action to be unregistered
  48441. * @return whether the action has been unregistered
  48442. */
  48443. ActionManager.prototype.unregisterAction = function (action) {
  48444. var index = this.actions.indexOf(action);
  48445. if (index !== -1) {
  48446. this.actions.splice(index, 1);
  48447. ActionManager.Triggers[action.trigger] -= 1;
  48448. if (ActionManager.Triggers[action.trigger] === 0) {
  48449. delete ActionManager.Triggers[action.trigger];
  48450. }
  48451. delete action._actionManager;
  48452. return true;
  48453. }
  48454. return false;
  48455. };
  48456. /**
  48457. * Process a specific trigger
  48458. * @param {number} trigger - the trigger to process
  48459. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48460. */
  48461. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48462. for (var index = 0; index < this.actions.length; index++) {
  48463. var action = this.actions[index];
  48464. if (action.trigger === trigger) {
  48465. if (evt) {
  48466. if (trigger === ActionManager.OnKeyUpTrigger
  48467. || trigger === ActionManager.OnKeyDownTrigger) {
  48468. var parameter = action.getTriggerParameter();
  48469. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48470. if (!parameter.toLowerCase) {
  48471. continue;
  48472. }
  48473. var lowerCase = parameter.toLowerCase();
  48474. if (lowerCase !== evt.sourceEvent.key) {
  48475. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48476. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48477. if (actualkey !== lowerCase) {
  48478. continue;
  48479. }
  48480. }
  48481. }
  48482. }
  48483. }
  48484. action._executeCurrent(evt);
  48485. }
  48486. }
  48487. };
  48488. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48489. var properties = propertyPath.split(".");
  48490. for (var index = 0; index < properties.length - 1; index++) {
  48491. target = target[properties[index]];
  48492. }
  48493. return target;
  48494. };
  48495. ActionManager.prototype._getProperty = function (propertyPath) {
  48496. var properties = propertyPath.split(".");
  48497. return properties[properties.length - 1];
  48498. };
  48499. ActionManager.prototype.serialize = function (name) {
  48500. var root = {
  48501. children: new Array(),
  48502. name: name,
  48503. type: 3,
  48504. properties: new Array() // Empty for root but required
  48505. };
  48506. for (var i = 0; i < this.actions.length; i++) {
  48507. var triggerObject = {
  48508. type: 0,
  48509. children: new Array(),
  48510. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48511. properties: new Array()
  48512. };
  48513. var triggerOptions = this.actions[i].triggerOptions;
  48514. if (triggerOptions && typeof triggerOptions !== "number") {
  48515. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48516. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48517. }
  48518. else {
  48519. var parameter = {};
  48520. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48521. if (triggerOptions.parameter.mesh) {
  48522. parameter._meshId = triggerOptions.parameter.mesh.id;
  48523. }
  48524. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48525. }
  48526. }
  48527. // Serialize child action, recursively
  48528. this.actions[i].serialize(triggerObject);
  48529. // Add serialized trigger
  48530. root.children.push(triggerObject);
  48531. }
  48532. return root;
  48533. };
  48534. ActionManager.Parse = function (parsedActions, object, scene) {
  48535. var actionManager = new ActionManager(scene);
  48536. if (object === null)
  48537. scene.actionManager = actionManager;
  48538. else
  48539. object.actionManager = actionManager;
  48540. // instanciate a new object
  48541. var instanciate = function (name, params) {
  48542. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48543. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48544. newInstance.constructor.apply(newInstance, params);
  48545. return newInstance;
  48546. };
  48547. var parseParameter = function (name, value, target, propertyPath) {
  48548. if (propertyPath === null) {
  48549. // String, boolean or float
  48550. var floatValue = parseFloat(value);
  48551. if (value === "true" || value === "false")
  48552. return value === "true";
  48553. else
  48554. return isNaN(floatValue) ? value : floatValue;
  48555. }
  48556. var effectiveTarget = propertyPath.split(".");
  48557. var values = value.split(",");
  48558. // Get effective Target
  48559. for (var i = 0; i < effectiveTarget.length; i++) {
  48560. target = target[effectiveTarget[i]];
  48561. }
  48562. // Return appropriate value with its type
  48563. if (typeof (target) === "boolean")
  48564. return values[0] === "true";
  48565. if (typeof (target) === "string")
  48566. return values[0];
  48567. // Parameters with multiple values such as Vector3 etc.
  48568. var split = new Array();
  48569. for (var i = 0; i < values.length; i++)
  48570. split.push(parseFloat(values[i]));
  48571. if (target instanceof BABYLON.Vector3)
  48572. return BABYLON.Vector3.FromArray(split);
  48573. if (target instanceof BABYLON.Vector4)
  48574. return BABYLON.Vector4.FromArray(split);
  48575. if (target instanceof BABYLON.Color3)
  48576. return BABYLON.Color3.FromArray(split);
  48577. if (target instanceof BABYLON.Color4)
  48578. return BABYLON.Color4.FromArray(split);
  48579. return parseFloat(values[0]);
  48580. };
  48581. // traverse graph per trigger
  48582. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48583. if (combineArray === void 0) { combineArray = null; }
  48584. if (parsedAction.detached)
  48585. return;
  48586. var parameters = new Array();
  48587. var target = null;
  48588. var propertyPath = null;
  48589. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48590. // Parameters
  48591. if (parsedAction.type === 2)
  48592. parameters.push(actionManager);
  48593. else
  48594. parameters.push(trigger);
  48595. if (combine) {
  48596. var actions = new Array();
  48597. for (var j = 0; j < parsedAction.combine.length; j++) {
  48598. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48599. }
  48600. parameters.push(actions);
  48601. }
  48602. else {
  48603. for (var i = 0; i < parsedAction.properties.length; i++) {
  48604. var value = parsedAction.properties[i].value;
  48605. var name = parsedAction.properties[i].name;
  48606. var targetType = parsedAction.properties[i].targetType;
  48607. if (name === "target")
  48608. if (targetType !== null && targetType === "SceneProperties")
  48609. value = target = scene;
  48610. else
  48611. value = target = scene.getNodeByName(value);
  48612. else if (name === "parent")
  48613. value = scene.getNodeByName(value);
  48614. else if (name === "sound")
  48615. value = scene.getSoundByName(value);
  48616. else if (name !== "propertyPath") {
  48617. if (parsedAction.type === 2 && name === "operator")
  48618. value = BABYLON.ValueCondition[value];
  48619. else
  48620. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48621. }
  48622. else {
  48623. propertyPath = value;
  48624. }
  48625. parameters.push(value);
  48626. }
  48627. }
  48628. if (combineArray === null) {
  48629. parameters.push(condition);
  48630. }
  48631. else {
  48632. parameters.push(null);
  48633. }
  48634. // If interpolate value action
  48635. if (parsedAction.name === "InterpolateValueAction") {
  48636. var param = parameters[parameters.length - 2];
  48637. parameters[parameters.length - 1] = param;
  48638. parameters[parameters.length - 2] = condition;
  48639. }
  48640. // Action or condition(s) and not CombineAction
  48641. var newAction = instanciate(parsedAction.name, parameters);
  48642. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48643. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48644. if (action)
  48645. action.then(nothing);
  48646. else
  48647. actionManager.registerAction(nothing);
  48648. action = nothing;
  48649. }
  48650. if (combineArray === null) {
  48651. if (newAction instanceof BABYLON.Condition) {
  48652. condition = newAction;
  48653. newAction = action;
  48654. }
  48655. else {
  48656. condition = null;
  48657. if (action)
  48658. action.then(newAction);
  48659. else
  48660. actionManager.registerAction(newAction);
  48661. }
  48662. }
  48663. else {
  48664. combineArray.push(newAction);
  48665. }
  48666. for (var i = 0; i < parsedAction.children.length; i++)
  48667. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48668. };
  48669. // triggers
  48670. for (var i = 0; i < parsedActions.children.length; i++) {
  48671. var triggerParams;
  48672. var trigger = parsedActions.children[i];
  48673. if (trigger.properties.length > 0) {
  48674. var param = trigger.properties[0].value;
  48675. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48676. if (value._meshId) {
  48677. value.mesh = scene.getMeshByID(value._meshId);
  48678. }
  48679. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48680. }
  48681. else
  48682. triggerParams = ActionManager[trigger.name];
  48683. for (var j = 0; j < trigger.children.length; j++) {
  48684. if (!trigger.detached)
  48685. traverse(trigger.children[j], triggerParams, null, null);
  48686. }
  48687. }
  48688. };
  48689. ActionManager.GetTriggerName = function (trigger) {
  48690. switch (trigger) {
  48691. case 0: return "NothingTrigger";
  48692. case 1: return "OnPickTrigger";
  48693. case 2: return "OnLeftPickTrigger";
  48694. case 3: return "OnRightPickTrigger";
  48695. case 4: return "OnCenterPickTrigger";
  48696. case 5: return "OnPickDownTrigger";
  48697. case 6: return "OnPickUpTrigger";
  48698. case 7: return "OnLongPressTrigger";
  48699. case 8: return "OnPointerOverTrigger";
  48700. case 9: return "OnPointerOutTrigger";
  48701. case 10: return "OnEveryFrameTrigger";
  48702. case 11: return "OnIntersectionEnterTrigger";
  48703. case 12: return "OnIntersectionExitTrigger";
  48704. case 13: return "OnKeyDownTrigger";
  48705. case 14: return "OnKeyUpTrigger";
  48706. case 15: return "OnPickOutTrigger";
  48707. default: return "";
  48708. }
  48709. };
  48710. // Statics
  48711. ActionManager._NothingTrigger = 0;
  48712. ActionManager._OnPickTrigger = 1;
  48713. ActionManager._OnLeftPickTrigger = 2;
  48714. ActionManager._OnRightPickTrigger = 3;
  48715. ActionManager._OnCenterPickTrigger = 4;
  48716. ActionManager._OnPickDownTrigger = 5;
  48717. ActionManager._OnDoublePickTrigger = 6;
  48718. ActionManager._OnPickUpTrigger = 7;
  48719. ActionManager._OnLongPressTrigger = 8;
  48720. ActionManager._OnPointerOverTrigger = 9;
  48721. ActionManager._OnPointerOutTrigger = 10;
  48722. ActionManager._OnEveryFrameTrigger = 11;
  48723. ActionManager._OnIntersectionEnterTrigger = 12;
  48724. ActionManager._OnIntersectionExitTrigger = 13;
  48725. ActionManager._OnKeyDownTrigger = 14;
  48726. ActionManager._OnKeyUpTrigger = 15;
  48727. ActionManager._OnPickOutTrigger = 16;
  48728. ActionManager.Triggers = {};
  48729. return ActionManager;
  48730. }());
  48731. BABYLON.ActionManager = ActionManager;
  48732. })(BABYLON || (BABYLON = {}));
  48733. //# sourceMappingURL=babylon.actionManager.js.map
  48734. var BABYLON;
  48735. (function (BABYLON) {
  48736. var InterpolateValueAction = /** @class */ (function (_super) {
  48737. __extends(InterpolateValueAction, _super);
  48738. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48739. if (duration === void 0) { duration = 1000; }
  48740. var _this = _super.call(this, triggerOptions, condition) || this;
  48741. _this.propertyPath = propertyPath;
  48742. _this.value = value;
  48743. _this.duration = duration;
  48744. _this.stopOtherAnimations = stopOtherAnimations;
  48745. _this.onInterpolationDone = onInterpolationDone;
  48746. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48747. _this._target = _this._effectiveTarget = target;
  48748. return _this;
  48749. }
  48750. InterpolateValueAction.prototype._prepare = function () {
  48751. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48752. this._property = this._getProperty(this.propertyPath);
  48753. };
  48754. InterpolateValueAction.prototype.execute = function () {
  48755. var _this = this;
  48756. var scene = this._actionManager.getScene();
  48757. var keys = [
  48758. {
  48759. frame: 0,
  48760. value: this._effectiveTarget[this._property]
  48761. }, {
  48762. frame: 100,
  48763. value: this.value
  48764. }
  48765. ];
  48766. var dataType;
  48767. if (typeof this.value === "number") {
  48768. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48769. }
  48770. else if (this.value instanceof BABYLON.Color3) {
  48771. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48772. }
  48773. else if (this.value instanceof BABYLON.Vector3) {
  48774. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48775. }
  48776. else if (this.value instanceof BABYLON.Matrix) {
  48777. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48778. }
  48779. else if (this.value instanceof BABYLON.Quaternion) {
  48780. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48781. }
  48782. else {
  48783. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48784. return;
  48785. }
  48786. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48787. animation.setKeys(keys);
  48788. if (this.stopOtherAnimations) {
  48789. scene.stopAnimation(this._effectiveTarget);
  48790. }
  48791. var wrapper = function () {
  48792. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48793. if (_this.onInterpolationDone) {
  48794. _this.onInterpolationDone();
  48795. }
  48796. };
  48797. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48798. };
  48799. InterpolateValueAction.prototype.serialize = function (parent) {
  48800. return _super.prototype._serialize.call(this, {
  48801. name: "InterpolateValueAction",
  48802. properties: [
  48803. BABYLON.Action._GetTargetProperty(this._target),
  48804. { name: "propertyPath", value: this.propertyPath },
  48805. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48806. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48807. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48808. ]
  48809. }, parent);
  48810. };
  48811. return InterpolateValueAction;
  48812. }(BABYLON.Action));
  48813. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48814. })(BABYLON || (BABYLON = {}));
  48815. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48816. var BABYLON;
  48817. (function (BABYLON) {
  48818. var SwitchBooleanAction = /** @class */ (function (_super) {
  48819. __extends(SwitchBooleanAction, _super);
  48820. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48821. var _this = _super.call(this, triggerOptions, condition) || this;
  48822. _this.propertyPath = propertyPath;
  48823. _this._target = _this._effectiveTarget = target;
  48824. return _this;
  48825. }
  48826. SwitchBooleanAction.prototype._prepare = function () {
  48827. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48828. this._property = this._getProperty(this.propertyPath);
  48829. };
  48830. SwitchBooleanAction.prototype.execute = function () {
  48831. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48832. };
  48833. SwitchBooleanAction.prototype.serialize = function (parent) {
  48834. return _super.prototype._serialize.call(this, {
  48835. name: "SwitchBooleanAction",
  48836. properties: [
  48837. BABYLON.Action._GetTargetProperty(this._target),
  48838. { name: "propertyPath", value: this.propertyPath }
  48839. ]
  48840. }, parent);
  48841. };
  48842. return SwitchBooleanAction;
  48843. }(BABYLON.Action));
  48844. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48845. var SetStateAction = /** @class */ (function (_super) {
  48846. __extends(SetStateAction, _super);
  48847. function SetStateAction(triggerOptions, target, value, condition) {
  48848. var _this = _super.call(this, triggerOptions, condition) || this;
  48849. _this.value = value;
  48850. _this._target = target;
  48851. return _this;
  48852. }
  48853. SetStateAction.prototype.execute = function () {
  48854. this._target.state = this.value;
  48855. };
  48856. SetStateAction.prototype.serialize = function (parent) {
  48857. return _super.prototype._serialize.call(this, {
  48858. name: "SetStateAction",
  48859. properties: [
  48860. BABYLON.Action._GetTargetProperty(this._target),
  48861. { name: "value", value: this.value }
  48862. ]
  48863. }, parent);
  48864. };
  48865. return SetStateAction;
  48866. }(BABYLON.Action));
  48867. BABYLON.SetStateAction = SetStateAction;
  48868. var SetValueAction = /** @class */ (function (_super) {
  48869. __extends(SetValueAction, _super);
  48870. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48871. var _this = _super.call(this, triggerOptions, condition) || this;
  48872. _this.propertyPath = propertyPath;
  48873. _this.value = value;
  48874. _this._target = _this._effectiveTarget = target;
  48875. return _this;
  48876. }
  48877. SetValueAction.prototype._prepare = function () {
  48878. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48879. this._property = this._getProperty(this.propertyPath);
  48880. };
  48881. SetValueAction.prototype.execute = function () {
  48882. this._effectiveTarget[this._property] = this.value;
  48883. if (this._target.markAsDirty) {
  48884. this._target.markAsDirty(this._property);
  48885. }
  48886. };
  48887. SetValueAction.prototype.serialize = function (parent) {
  48888. return _super.prototype._serialize.call(this, {
  48889. name: "SetValueAction",
  48890. properties: [
  48891. BABYLON.Action._GetTargetProperty(this._target),
  48892. { name: "propertyPath", value: this.propertyPath },
  48893. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48894. ]
  48895. }, parent);
  48896. };
  48897. return SetValueAction;
  48898. }(BABYLON.Action));
  48899. BABYLON.SetValueAction = SetValueAction;
  48900. var IncrementValueAction = /** @class */ (function (_super) {
  48901. __extends(IncrementValueAction, _super);
  48902. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48903. var _this = _super.call(this, triggerOptions, condition) || this;
  48904. _this.propertyPath = propertyPath;
  48905. _this.value = value;
  48906. _this._target = _this._effectiveTarget = target;
  48907. return _this;
  48908. }
  48909. IncrementValueAction.prototype._prepare = function () {
  48910. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48911. this._property = this._getProperty(this.propertyPath);
  48912. if (typeof this._effectiveTarget[this._property] !== "number") {
  48913. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48914. }
  48915. };
  48916. IncrementValueAction.prototype.execute = function () {
  48917. this._effectiveTarget[this._property] += this.value;
  48918. if (this._target.markAsDirty) {
  48919. this._target.markAsDirty(this._property);
  48920. }
  48921. };
  48922. IncrementValueAction.prototype.serialize = function (parent) {
  48923. return _super.prototype._serialize.call(this, {
  48924. name: "IncrementValueAction",
  48925. properties: [
  48926. BABYLON.Action._GetTargetProperty(this._target),
  48927. { name: "propertyPath", value: this.propertyPath },
  48928. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48929. ]
  48930. }, parent);
  48931. };
  48932. return IncrementValueAction;
  48933. }(BABYLON.Action));
  48934. BABYLON.IncrementValueAction = IncrementValueAction;
  48935. var PlayAnimationAction = /** @class */ (function (_super) {
  48936. __extends(PlayAnimationAction, _super);
  48937. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48938. var _this = _super.call(this, triggerOptions, condition) || this;
  48939. _this.from = from;
  48940. _this.to = to;
  48941. _this.loop = loop;
  48942. _this._target = target;
  48943. return _this;
  48944. }
  48945. PlayAnimationAction.prototype._prepare = function () {
  48946. };
  48947. PlayAnimationAction.prototype.execute = function () {
  48948. var scene = this._actionManager.getScene();
  48949. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48950. };
  48951. PlayAnimationAction.prototype.serialize = function (parent) {
  48952. return _super.prototype._serialize.call(this, {
  48953. name: "PlayAnimationAction",
  48954. properties: [
  48955. BABYLON.Action._GetTargetProperty(this._target),
  48956. { name: "from", value: String(this.from) },
  48957. { name: "to", value: String(this.to) },
  48958. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48959. ]
  48960. }, parent);
  48961. };
  48962. return PlayAnimationAction;
  48963. }(BABYLON.Action));
  48964. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48965. var StopAnimationAction = /** @class */ (function (_super) {
  48966. __extends(StopAnimationAction, _super);
  48967. function StopAnimationAction(triggerOptions, target, condition) {
  48968. var _this = _super.call(this, triggerOptions, condition) || this;
  48969. _this._target = target;
  48970. return _this;
  48971. }
  48972. StopAnimationAction.prototype._prepare = function () {
  48973. };
  48974. StopAnimationAction.prototype.execute = function () {
  48975. var scene = this._actionManager.getScene();
  48976. scene.stopAnimation(this._target);
  48977. };
  48978. StopAnimationAction.prototype.serialize = function (parent) {
  48979. return _super.prototype._serialize.call(this, {
  48980. name: "StopAnimationAction",
  48981. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48982. }, parent);
  48983. };
  48984. return StopAnimationAction;
  48985. }(BABYLON.Action));
  48986. BABYLON.StopAnimationAction = StopAnimationAction;
  48987. var DoNothingAction = /** @class */ (function (_super) {
  48988. __extends(DoNothingAction, _super);
  48989. function DoNothingAction(triggerOptions, condition) {
  48990. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48991. return _super.call(this, triggerOptions, condition) || this;
  48992. }
  48993. DoNothingAction.prototype.execute = function () {
  48994. };
  48995. DoNothingAction.prototype.serialize = function (parent) {
  48996. return _super.prototype._serialize.call(this, {
  48997. name: "DoNothingAction",
  48998. properties: []
  48999. }, parent);
  49000. };
  49001. return DoNothingAction;
  49002. }(BABYLON.Action));
  49003. BABYLON.DoNothingAction = DoNothingAction;
  49004. var CombineAction = /** @class */ (function (_super) {
  49005. __extends(CombineAction, _super);
  49006. function CombineAction(triggerOptions, children, condition) {
  49007. var _this = _super.call(this, triggerOptions, condition) || this;
  49008. _this.children = children;
  49009. return _this;
  49010. }
  49011. CombineAction.prototype._prepare = function () {
  49012. for (var index = 0; index < this.children.length; index++) {
  49013. this.children[index]._actionManager = this._actionManager;
  49014. this.children[index]._prepare();
  49015. }
  49016. };
  49017. CombineAction.prototype.execute = function (evt) {
  49018. for (var index = 0; index < this.children.length; index++) {
  49019. this.children[index].execute(evt);
  49020. }
  49021. };
  49022. CombineAction.prototype.serialize = function (parent) {
  49023. var serializationObject = _super.prototype._serialize.call(this, {
  49024. name: "CombineAction",
  49025. properties: [],
  49026. combine: []
  49027. }, parent);
  49028. for (var i = 0; i < this.children.length; i++) {
  49029. serializationObject.combine.push(this.children[i].serialize(null));
  49030. }
  49031. return serializationObject;
  49032. };
  49033. return CombineAction;
  49034. }(BABYLON.Action));
  49035. BABYLON.CombineAction = CombineAction;
  49036. var ExecuteCodeAction = /** @class */ (function (_super) {
  49037. __extends(ExecuteCodeAction, _super);
  49038. function ExecuteCodeAction(triggerOptions, func, condition) {
  49039. var _this = _super.call(this, triggerOptions, condition) || this;
  49040. _this.func = func;
  49041. return _this;
  49042. }
  49043. ExecuteCodeAction.prototype.execute = function (evt) {
  49044. this.func(evt);
  49045. };
  49046. return ExecuteCodeAction;
  49047. }(BABYLON.Action));
  49048. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49049. var SetParentAction = /** @class */ (function (_super) {
  49050. __extends(SetParentAction, _super);
  49051. function SetParentAction(triggerOptions, target, parent, condition) {
  49052. var _this = _super.call(this, triggerOptions, condition) || this;
  49053. _this._target = target;
  49054. _this._parent = parent;
  49055. return _this;
  49056. }
  49057. SetParentAction.prototype._prepare = function () {
  49058. };
  49059. SetParentAction.prototype.execute = function () {
  49060. if (this._target.parent === this._parent) {
  49061. return;
  49062. }
  49063. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49064. invertParentWorldMatrix.invert();
  49065. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49066. this._target.parent = this._parent;
  49067. };
  49068. SetParentAction.prototype.serialize = function (parent) {
  49069. return _super.prototype._serialize.call(this, {
  49070. name: "SetParentAction",
  49071. properties: [
  49072. BABYLON.Action._GetTargetProperty(this._target),
  49073. BABYLON.Action._GetTargetProperty(this._parent),
  49074. ]
  49075. }, parent);
  49076. };
  49077. return SetParentAction;
  49078. }(BABYLON.Action));
  49079. BABYLON.SetParentAction = SetParentAction;
  49080. var PlaySoundAction = /** @class */ (function (_super) {
  49081. __extends(PlaySoundAction, _super);
  49082. function PlaySoundAction(triggerOptions, sound, condition) {
  49083. var _this = _super.call(this, triggerOptions, condition) || this;
  49084. _this._sound = sound;
  49085. return _this;
  49086. }
  49087. PlaySoundAction.prototype._prepare = function () {
  49088. };
  49089. PlaySoundAction.prototype.execute = function () {
  49090. if (this._sound !== undefined)
  49091. this._sound.play();
  49092. };
  49093. PlaySoundAction.prototype.serialize = function (parent) {
  49094. return _super.prototype._serialize.call(this, {
  49095. name: "PlaySoundAction",
  49096. properties: [{ name: "sound", value: this._sound.name }]
  49097. }, parent);
  49098. };
  49099. return PlaySoundAction;
  49100. }(BABYLON.Action));
  49101. BABYLON.PlaySoundAction = PlaySoundAction;
  49102. var StopSoundAction = /** @class */ (function (_super) {
  49103. __extends(StopSoundAction, _super);
  49104. function StopSoundAction(triggerOptions, sound, condition) {
  49105. var _this = _super.call(this, triggerOptions, condition) || this;
  49106. _this._sound = sound;
  49107. return _this;
  49108. }
  49109. StopSoundAction.prototype._prepare = function () {
  49110. };
  49111. StopSoundAction.prototype.execute = function () {
  49112. if (this._sound !== undefined)
  49113. this._sound.stop();
  49114. };
  49115. StopSoundAction.prototype.serialize = function (parent) {
  49116. return _super.prototype._serialize.call(this, {
  49117. name: "StopSoundAction",
  49118. properties: [{ name: "sound", value: this._sound.name }]
  49119. }, parent);
  49120. };
  49121. return StopSoundAction;
  49122. }(BABYLON.Action));
  49123. BABYLON.StopSoundAction = StopSoundAction;
  49124. })(BABYLON || (BABYLON = {}));
  49125. //# sourceMappingURL=babylon.directActions.js.map
  49126. var BABYLON;
  49127. (function (BABYLON) {
  49128. var SpriteManager = /** @class */ (function () {
  49129. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49130. if (epsilon === void 0) { epsilon = 0.01; }
  49131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49132. this.name = name;
  49133. this.sprites = new Array();
  49134. this.renderingGroupId = 0;
  49135. this.layerMask = 0x0FFFFFFF;
  49136. this.fogEnabled = true;
  49137. this.isPickable = false;
  49138. /**
  49139. * An event triggered when the manager is disposed.
  49140. * @type {BABYLON.Observable}
  49141. */
  49142. this.onDisposeObservable = new BABYLON.Observable();
  49143. this._vertexBuffers = {};
  49144. this._capacity = capacity;
  49145. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49146. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49147. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49148. if (cellSize.width && cellSize.height) {
  49149. this.cellWidth = cellSize.width;
  49150. this.cellHeight = cellSize.height;
  49151. }
  49152. else if (cellSize !== undefined) {
  49153. this.cellWidth = cellSize;
  49154. this.cellHeight = cellSize;
  49155. }
  49156. else {
  49157. return;
  49158. }
  49159. this._epsilon = epsilon;
  49160. this._scene = scene;
  49161. this._scene.spriteManagers.push(this);
  49162. var indices = [];
  49163. var index = 0;
  49164. for (var count = 0; count < capacity; count++) {
  49165. indices.push(index);
  49166. indices.push(index + 1);
  49167. indices.push(index + 2);
  49168. indices.push(index);
  49169. indices.push(index + 2);
  49170. indices.push(index + 3);
  49171. index += 4;
  49172. }
  49173. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49174. // VBO
  49175. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49176. this._vertexData = new Float32Array(capacity * 16 * 4);
  49177. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49178. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49179. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49180. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49181. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49182. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49183. this._vertexBuffers["options"] = options;
  49184. this._vertexBuffers["cellInfo"] = cellInfo;
  49185. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49186. // Effects
  49187. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49188. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49189. }
  49190. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49191. set: function (callback) {
  49192. if (this._onDisposeObserver) {
  49193. this.onDisposeObservable.remove(this._onDisposeObserver);
  49194. }
  49195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49196. },
  49197. enumerable: true,
  49198. configurable: true
  49199. });
  49200. Object.defineProperty(SpriteManager.prototype, "texture", {
  49201. get: function () {
  49202. return this._spriteTexture;
  49203. },
  49204. set: function (value) {
  49205. this._spriteTexture = value;
  49206. },
  49207. enumerable: true,
  49208. configurable: true
  49209. });
  49210. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49211. var arrayOffset = index * 16;
  49212. if (offsetX === 0)
  49213. offsetX = this._epsilon;
  49214. else if (offsetX === 1)
  49215. offsetX = 1 - this._epsilon;
  49216. if (offsetY === 0)
  49217. offsetY = this._epsilon;
  49218. else if (offsetY === 1)
  49219. offsetY = 1 - this._epsilon;
  49220. this._vertexData[arrayOffset] = sprite.position.x;
  49221. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49222. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49223. this._vertexData[arrayOffset + 3] = sprite.angle;
  49224. this._vertexData[arrayOffset + 4] = sprite.width;
  49225. this._vertexData[arrayOffset + 5] = sprite.height;
  49226. this._vertexData[arrayOffset + 6] = offsetX;
  49227. this._vertexData[arrayOffset + 7] = offsetY;
  49228. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49229. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49230. var offset = (sprite.cellIndex / rowSize) >> 0;
  49231. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49232. this._vertexData[arrayOffset + 11] = offset;
  49233. // Color
  49234. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49235. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49236. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49237. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49238. };
  49239. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49240. var count = Math.min(this._capacity, this.sprites.length);
  49241. var min = BABYLON.Vector3.Zero();
  49242. var max = BABYLON.Vector3.Zero();
  49243. var distance = Number.MAX_VALUE;
  49244. var currentSprite = null;
  49245. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49246. var cameraView = camera.getViewMatrix();
  49247. for (var index = 0; index < count; index++) {
  49248. var sprite = this.sprites[index];
  49249. if (!sprite) {
  49250. continue;
  49251. }
  49252. if (predicate) {
  49253. if (!predicate(sprite)) {
  49254. continue;
  49255. }
  49256. }
  49257. else if (!sprite.isPickable) {
  49258. continue;
  49259. }
  49260. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49261. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49262. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49263. if (ray.intersectsBoxMinMax(min, max)) {
  49264. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49265. if (distance > currentDistance) {
  49266. distance = currentDistance;
  49267. currentSprite = sprite;
  49268. if (fastCheck) {
  49269. break;
  49270. }
  49271. }
  49272. }
  49273. }
  49274. if (currentSprite) {
  49275. var result = new BABYLON.PickingInfo();
  49276. result.hit = true;
  49277. result.pickedSprite = currentSprite;
  49278. result.distance = distance;
  49279. return result;
  49280. }
  49281. return null;
  49282. };
  49283. SpriteManager.prototype.render = function () {
  49284. // Check
  49285. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49286. return;
  49287. var engine = this._scene.getEngine();
  49288. var baseSize = this._spriteTexture.getBaseSize();
  49289. // Sprites
  49290. var deltaTime = engine.getDeltaTime();
  49291. var max = Math.min(this._capacity, this.sprites.length);
  49292. var rowSize = baseSize.width / this.cellWidth;
  49293. var offset = 0;
  49294. for (var index = 0; index < max; index++) {
  49295. var sprite = this.sprites[index];
  49296. if (!sprite) {
  49297. continue;
  49298. }
  49299. sprite._animate(deltaTime);
  49300. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49301. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49302. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49303. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49304. }
  49305. this._buffer.update(this._vertexData);
  49306. // Render
  49307. var effect = this._effectBase;
  49308. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49309. effect = this._effectFog;
  49310. }
  49311. engine.enableEffect(effect);
  49312. var viewMatrix = this._scene.getViewMatrix();
  49313. effect.setTexture("diffuseSampler", this._spriteTexture);
  49314. effect.setMatrix("view", viewMatrix);
  49315. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49316. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49317. // Fog
  49318. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49319. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49320. effect.setColor3("vFogColor", this._scene.fogColor);
  49321. }
  49322. // VBOs
  49323. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49324. // Draw order
  49325. engine.setDepthFunctionToLessOrEqual();
  49326. effect.setBool("alphaTest", true);
  49327. engine.setColorWrite(false);
  49328. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49329. engine.setColorWrite(true);
  49330. effect.setBool("alphaTest", false);
  49331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49332. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49334. };
  49335. SpriteManager.prototype.dispose = function () {
  49336. if (this._buffer) {
  49337. this._buffer.dispose();
  49338. this._buffer = null;
  49339. }
  49340. if (this._indexBuffer) {
  49341. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49342. this._indexBuffer = null;
  49343. }
  49344. if (this._spriteTexture) {
  49345. this._spriteTexture.dispose();
  49346. this._spriteTexture = null;
  49347. }
  49348. // Remove from scene
  49349. var index = this._scene.spriteManagers.indexOf(this);
  49350. this._scene.spriteManagers.splice(index, 1);
  49351. // Callback
  49352. this.onDisposeObservable.notifyObservers(this);
  49353. this.onDisposeObservable.clear();
  49354. };
  49355. return SpriteManager;
  49356. }());
  49357. BABYLON.SpriteManager = SpriteManager;
  49358. })(BABYLON || (BABYLON = {}));
  49359. //# sourceMappingURL=babylon.spriteManager.js.map
  49360. var BABYLON;
  49361. (function (BABYLON) {
  49362. var Sprite = /** @class */ (function () {
  49363. function Sprite(name, manager) {
  49364. this.name = name;
  49365. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49366. this.width = 1.0;
  49367. this.height = 1.0;
  49368. this.angle = 0;
  49369. this.cellIndex = 0;
  49370. this.invertU = 0;
  49371. this.invertV = 0;
  49372. this.animations = new Array();
  49373. this.isPickable = false;
  49374. this._animationStarted = false;
  49375. this._loopAnimation = false;
  49376. this._fromIndex = 0;
  49377. this._toIndex = 0;
  49378. this._delay = 0;
  49379. this._direction = 1;
  49380. this._time = 0;
  49381. this._manager = manager;
  49382. this._manager.sprites.push(this);
  49383. this.position = BABYLON.Vector3.Zero();
  49384. }
  49385. Object.defineProperty(Sprite.prototype, "size", {
  49386. get: function () {
  49387. return this.width;
  49388. },
  49389. set: function (value) {
  49390. this.width = value;
  49391. this.height = value;
  49392. },
  49393. enumerable: true,
  49394. configurable: true
  49395. });
  49396. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49397. this._fromIndex = from;
  49398. this._toIndex = to;
  49399. this._loopAnimation = loop;
  49400. this._delay = delay;
  49401. this._animationStarted = true;
  49402. this._direction = from < to ? 1 : -1;
  49403. this.cellIndex = from;
  49404. this._time = 0;
  49405. this._onAnimationEnd = onAnimationEnd;
  49406. };
  49407. Sprite.prototype.stopAnimation = function () {
  49408. this._animationStarted = false;
  49409. };
  49410. Sprite.prototype._animate = function (deltaTime) {
  49411. if (!this._animationStarted)
  49412. return;
  49413. this._time += deltaTime;
  49414. if (this._time > this._delay) {
  49415. this._time = this._time % this._delay;
  49416. this.cellIndex += this._direction;
  49417. if (this.cellIndex > this._toIndex) {
  49418. if (this._loopAnimation) {
  49419. this.cellIndex = this._fromIndex;
  49420. }
  49421. else {
  49422. this.cellIndex = this._toIndex;
  49423. this._animationStarted = false;
  49424. if (this._onAnimationEnd) {
  49425. this._onAnimationEnd();
  49426. }
  49427. if (this.disposeWhenFinishedAnimating) {
  49428. this.dispose();
  49429. }
  49430. }
  49431. }
  49432. }
  49433. };
  49434. Sprite.prototype.dispose = function () {
  49435. for (var i = 0; i < this._manager.sprites.length; i++) {
  49436. if (this._manager.sprites[i] == this) {
  49437. this._manager.sprites.splice(i, 1);
  49438. }
  49439. }
  49440. };
  49441. return Sprite;
  49442. }());
  49443. BABYLON.Sprite = Sprite;
  49444. })(BABYLON || (BABYLON = {}));
  49445. //# sourceMappingURL=babylon.sprite.js.map
  49446. var BABYLON;
  49447. (function (BABYLON) {
  49448. var IntersectionInfo = /** @class */ (function () {
  49449. function IntersectionInfo(bu, bv, distance) {
  49450. this.bu = bu;
  49451. this.bv = bv;
  49452. this.distance = distance;
  49453. this.faceId = 0;
  49454. this.subMeshId = 0;
  49455. }
  49456. return IntersectionInfo;
  49457. }());
  49458. BABYLON.IntersectionInfo = IntersectionInfo;
  49459. var PickingInfo = /** @class */ (function () {
  49460. function PickingInfo() {
  49461. this.hit = false;
  49462. this.distance = 0;
  49463. this.pickedPoint = null;
  49464. this.pickedMesh = null;
  49465. this.bu = 0;
  49466. this.bv = 0;
  49467. this.faceId = -1;
  49468. this.subMeshId = 0;
  49469. this.pickedSprite = null;
  49470. }
  49471. // Methods
  49472. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49473. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49474. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49475. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49476. return null;
  49477. }
  49478. var indices = this.pickedMesh.getIndices();
  49479. if (!indices) {
  49480. return null;
  49481. }
  49482. var result;
  49483. if (useVerticesNormals) {
  49484. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49485. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49486. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49487. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49488. normal0 = normal0.scale(this.bu);
  49489. normal1 = normal1.scale(this.bv);
  49490. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49491. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49492. }
  49493. else {
  49494. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49495. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49496. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49497. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49498. var p1p2 = vertex1.subtract(vertex2);
  49499. var p3p2 = vertex3.subtract(vertex2);
  49500. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49501. }
  49502. if (useWorldCoordinates) {
  49503. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49504. }
  49505. return BABYLON.Vector3.Normalize(result);
  49506. };
  49507. PickingInfo.prototype.getTextureCoordinates = function () {
  49508. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49509. return null;
  49510. }
  49511. var indices = this.pickedMesh.getIndices();
  49512. if (!indices) {
  49513. return null;
  49514. }
  49515. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49516. if (!uvs) {
  49517. return null;
  49518. }
  49519. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49520. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49521. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49522. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49523. uv1 = uv1.scale(this.bu);
  49524. uv2 = uv2.scale(this.bv);
  49525. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49526. };
  49527. return PickingInfo;
  49528. }());
  49529. BABYLON.PickingInfo = PickingInfo;
  49530. })(BABYLON || (BABYLON = {}));
  49531. //# sourceMappingURL=babylon.pickingInfo.js.map
  49532. var BABYLON;
  49533. (function (BABYLON) {
  49534. var Ray = /** @class */ (function () {
  49535. function Ray(origin, direction, length) {
  49536. if (length === void 0) { length = Number.MAX_VALUE; }
  49537. this.origin = origin;
  49538. this.direction = direction;
  49539. this.length = length;
  49540. }
  49541. // Methods
  49542. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49543. var d = 0.0;
  49544. var maxValue = Number.MAX_VALUE;
  49545. var inv;
  49546. var min;
  49547. var max;
  49548. var temp;
  49549. if (Math.abs(this.direction.x) < 0.0000001) {
  49550. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49551. return false;
  49552. }
  49553. }
  49554. else {
  49555. inv = 1.0 / this.direction.x;
  49556. min = (minimum.x - this.origin.x) * inv;
  49557. max = (maximum.x - this.origin.x) * inv;
  49558. if (max === -Infinity) {
  49559. max = Infinity;
  49560. }
  49561. if (min > max) {
  49562. temp = min;
  49563. min = max;
  49564. max = temp;
  49565. }
  49566. d = Math.max(min, d);
  49567. maxValue = Math.min(max, maxValue);
  49568. if (d > maxValue) {
  49569. return false;
  49570. }
  49571. }
  49572. if (Math.abs(this.direction.y) < 0.0000001) {
  49573. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49574. return false;
  49575. }
  49576. }
  49577. else {
  49578. inv = 1.0 / this.direction.y;
  49579. min = (minimum.y - this.origin.y) * inv;
  49580. max = (maximum.y - this.origin.y) * inv;
  49581. if (max === -Infinity) {
  49582. max = Infinity;
  49583. }
  49584. if (min > max) {
  49585. temp = min;
  49586. min = max;
  49587. max = temp;
  49588. }
  49589. d = Math.max(min, d);
  49590. maxValue = Math.min(max, maxValue);
  49591. if (d > maxValue) {
  49592. return false;
  49593. }
  49594. }
  49595. if (Math.abs(this.direction.z) < 0.0000001) {
  49596. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49597. return false;
  49598. }
  49599. }
  49600. else {
  49601. inv = 1.0 / this.direction.z;
  49602. min = (minimum.z - this.origin.z) * inv;
  49603. max = (maximum.z - this.origin.z) * inv;
  49604. if (max === -Infinity) {
  49605. max = Infinity;
  49606. }
  49607. if (min > max) {
  49608. temp = min;
  49609. min = max;
  49610. max = temp;
  49611. }
  49612. d = Math.max(min, d);
  49613. maxValue = Math.min(max, maxValue);
  49614. if (d > maxValue) {
  49615. return false;
  49616. }
  49617. }
  49618. return true;
  49619. };
  49620. Ray.prototype.intersectsBox = function (box) {
  49621. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49622. };
  49623. Ray.prototype.intersectsSphere = function (sphere) {
  49624. var x = sphere.center.x - this.origin.x;
  49625. var y = sphere.center.y - this.origin.y;
  49626. var z = sphere.center.z - this.origin.z;
  49627. var pyth = (x * x) + (y * y) + (z * z);
  49628. var rr = sphere.radius * sphere.radius;
  49629. if (pyth <= rr) {
  49630. return true;
  49631. }
  49632. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49633. if (dot < 0.0) {
  49634. return false;
  49635. }
  49636. var temp = pyth - (dot * dot);
  49637. return temp <= rr;
  49638. };
  49639. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49640. if (!this._edge1) {
  49641. this._edge1 = BABYLON.Vector3.Zero();
  49642. this._edge2 = BABYLON.Vector3.Zero();
  49643. this._pvec = BABYLON.Vector3.Zero();
  49644. this._tvec = BABYLON.Vector3.Zero();
  49645. this._qvec = BABYLON.Vector3.Zero();
  49646. }
  49647. vertex1.subtractToRef(vertex0, this._edge1);
  49648. vertex2.subtractToRef(vertex0, this._edge2);
  49649. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49650. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49651. if (det === 0) {
  49652. return null;
  49653. }
  49654. var invdet = 1 / det;
  49655. this.origin.subtractToRef(vertex0, this._tvec);
  49656. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49657. if (bu < 0 || bu > 1.0) {
  49658. return null;
  49659. }
  49660. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49661. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49662. if (bv < 0 || bu + bv > 1.0) {
  49663. return null;
  49664. }
  49665. //check if the distance is longer than the predefined length.
  49666. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49667. if (distance > this.length) {
  49668. return null;
  49669. }
  49670. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49671. };
  49672. Ray.prototype.intersectsPlane = function (plane) {
  49673. var distance;
  49674. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49675. if (Math.abs(result1) < 9.99999997475243E-07) {
  49676. return null;
  49677. }
  49678. else {
  49679. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49680. distance = (-plane.d - result2) / result1;
  49681. if (distance < 0.0) {
  49682. if (distance < -9.99999997475243E-07) {
  49683. return null;
  49684. }
  49685. else {
  49686. return 0;
  49687. }
  49688. }
  49689. return distance;
  49690. }
  49691. };
  49692. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49693. var tm = BABYLON.Tmp.Matrix[0];
  49694. mesh.getWorldMatrix().invertToRef(tm);
  49695. if (this._tmpRay) {
  49696. Ray.TransformToRef(this, tm, this._tmpRay);
  49697. }
  49698. else {
  49699. this._tmpRay = Ray.Transform(this, tm);
  49700. }
  49701. return mesh.intersects(this._tmpRay, fastCheck);
  49702. };
  49703. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49704. if (results) {
  49705. results.length = 0;
  49706. }
  49707. else {
  49708. results = [];
  49709. }
  49710. for (var i = 0; i < meshes.length; i++) {
  49711. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49712. if (pickInfo.hit) {
  49713. results.push(pickInfo);
  49714. }
  49715. }
  49716. results.sort(this._comparePickingInfo);
  49717. return results;
  49718. };
  49719. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49720. if (pickingInfoA.distance < pickingInfoB.distance) {
  49721. return -1;
  49722. }
  49723. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49724. return 1;
  49725. }
  49726. else {
  49727. return 0;
  49728. }
  49729. };
  49730. /**
  49731. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49732. * @param sega the first point of the segment to test the intersection against
  49733. * @param segb the second point of the segment to test the intersection against
  49734. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49735. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49736. */
  49737. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49738. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49739. var u = segb.subtract(sega);
  49740. var v = rsegb.subtract(this.origin);
  49741. var w = sega.subtract(this.origin);
  49742. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49743. var b = BABYLON.Vector3.Dot(u, v);
  49744. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49745. var d = BABYLON.Vector3.Dot(u, w);
  49746. var e = BABYLON.Vector3.Dot(v, w);
  49747. var D = a * c - b * b; // always >= 0
  49748. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49749. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49750. // compute the line parameters of the two closest points
  49751. if (D < Ray.smallnum) {
  49752. sN = 0.0; // force using point P0 on segment S1
  49753. sD = 1.0; // to prevent possible division by 0.0 later
  49754. tN = e;
  49755. tD = c;
  49756. }
  49757. else {
  49758. sN = (b * e - c * d);
  49759. tN = (a * e - b * d);
  49760. if (sN < 0.0) {
  49761. sN = 0.0;
  49762. tN = e;
  49763. tD = c;
  49764. }
  49765. else if (sN > sD) {
  49766. sN = sD;
  49767. tN = e + b;
  49768. tD = c;
  49769. }
  49770. }
  49771. if (tN < 0.0) {
  49772. tN = 0.0;
  49773. // recompute sc for this edge
  49774. if (-d < 0.0) {
  49775. sN = 0.0;
  49776. }
  49777. else if (-d > a)
  49778. sN = sD;
  49779. else {
  49780. sN = -d;
  49781. sD = a;
  49782. }
  49783. }
  49784. else if (tN > tD) {
  49785. tN = tD;
  49786. // recompute sc for this edge
  49787. if ((-d + b) < 0.0) {
  49788. sN = 0;
  49789. }
  49790. else if ((-d + b) > a) {
  49791. sN = sD;
  49792. }
  49793. else {
  49794. sN = (-d + b);
  49795. sD = a;
  49796. }
  49797. }
  49798. // finally do the division to get sc and tc
  49799. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49800. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49801. // get the difference of the two closest points
  49802. var qtc = v.multiplyByFloats(tc, tc, tc);
  49803. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49804. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49805. if (isIntersected) {
  49806. return qtc.length();
  49807. }
  49808. return -1;
  49809. };
  49810. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49811. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49812. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49813. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49814. this.direction.normalize();
  49815. return this;
  49816. };
  49817. // Statics
  49818. Ray.Zero = function () {
  49819. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49820. };
  49821. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49822. var result = Ray.Zero();
  49823. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49824. };
  49825. /**
  49826. * 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
  49827. * transformed to the given world matrix.
  49828. * @param origin The origin point
  49829. * @param end The end point
  49830. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49831. */
  49832. Ray.CreateNewFromTo = function (origin, end, world) {
  49833. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49834. var direction = end.subtract(origin);
  49835. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49836. direction.normalize();
  49837. return Ray.Transform(new Ray(origin, direction, length), world);
  49838. };
  49839. Ray.Transform = function (ray, matrix) {
  49840. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49841. Ray.TransformToRef(ray, matrix, result);
  49842. return result;
  49843. };
  49844. Ray.TransformToRef = function (ray, matrix, result) {
  49845. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49846. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49847. result.length = ray.length;
  49848. var dir = result.direction;
  49849. var len = dir.length();
  49850. if (!(len === 0 || len === 1)) {
  49851. var num = 1.0 / len;
  49852. dir.x *= num;
  49853. dir.y *= num;
  49854. dir.z *= num;
  49855. result.length *= len;
  49856. }
  49857. };
  49858. Ray.smallnum = 0.00000001;
  49859. Ray.rayl = 10e8;
  49860. return Ray;
  49861. }());
  49862. BABYLON.Ray = Ray;
  49863. })(BABYLON || (BABYLON = {}));
  49864. //# sourceMappingURL=babylon.ray.js.map
  49865. var BABYLON;
  49866. (function (BABYLON) {
  49867. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49868. if (boxMin.x > sphereCenter.x + sphereRadius)
  49869. return false;
  49870. if (sphereCenter.x - sphereRadius > boxMax.x)
  49871. return false;
  49872. if (boxMin.y > sphereCenter.y + sphereRadius)
  49873. return false;
  49874. if (sphereCenter.y - sphereRadius > boxMax.y)
  49875. return false;
  49876. if (boxMin.z > sphereCenter.z + sphereRadius)
  49877. return false;
  49878. if (sphereCenter.z - sphereRadius > boxMax.z)
  49879. return false;
  49880. return true;
  49881. };
  49882. var getLowestRoot = (function () {
  49883. var result = { root: 0, found: false };
  49884. return function (a, b, c, maxR) {
  49885. result.root = 0;
  49886. result.found = false;
  49887. var determinant = b * b - 4.0 * a * c;
  49888. if (determinant < 0)
  49889. return result;
  49890. var sqrtD = Math.sqrt(determinant);
  49891. var r1 = (-b - sqrtD) / (2.0 * a);
  49892. var r2 = (-b + sqrtD) / (2.0 * a);
  49893. if (r1 > r2) {
  49894. var temp = r2;
  49895. r2 = r1;
  49896. r1 = temp;
  49897. }
  49898. if (r1 > 0 && r1 < maxR) {
  49899. result.root = r1;
  49900. result.found = true;
  49901. return result;
  49902. }
  49903. if (r2 > 0 && r2 < maxR) {
  49904. result.root = r2;
  49905. result.found = true;
  49906. return result;
  49907. }
  49908. return result;
  49909. };
  49910. })();
  49911. var Collider = /** @class */ (function () {
  49912. function Collider() {
  49913. this._collisionPoint = BABYLON.Vector3.Zero();
  49914. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49915. this._tempVector = BABYLON.Vector3.Zero();
  49916. this._tempVector2 = BABYLON.Vector3.Zero();
  49917. this._tempVector3 = BABYLON.Vector3.Zero();
  49918. this._tempVector4 = BABYLON.Vector3.Zero();
  49919. this._edge = BABYLON.Vector3.Zero();
  49920. this._baseToVertex = BABYLON.Vector3.Zero();
  49921. this._destinationPoint = BABYLON.Vector3.Zero();
  49922. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49923. this._displacementVector = BABYLON.Vector3.Zero();
  49924. this._radius = BABYLON.Vector3.One();
  49925. this._retry = 0;
  49926. this._basePointWorld = BABYLON.Vector3.Zero();
  49927. this._velocityWorld = BABYLON.Vector3.Zero();
  49928. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49929. this._collisionMask = -1;
  49930. }
  49931. Object.defineProperty(Collider.prototype, "collisionMask", {
  49932. get: function () {
  49933. return this._collisionMask;
  49934. },
  49935. set: function (mask) {
  49936. this._collisionMask = !isNaN(mask) ? mask : -1;
  49937. },
  49938. enumerable: true,
  49939. configurable: true
  49940. });
  49941. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49942. /**
  49943. * Gets the plane normal used to compute the sliding response (in local space)
  49944. */
  49945. get: function () {
  49946. return this._slidePlaneNormal;
  49947. },
  49948. enumerable: true,
  49949. configurable: true
  49950. });
  49951. // Methods
  49952. Collider.prototype._initialize = function (source, dir, e) {
  49953. this._velocity = dir;
  49954. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49955. this._basePoint = source;
  49956. source.multiplyToRef(this._radius, this._basePointWorld);
  49957. dir.multiplyToRef(this._radius, this._velocityWorld);
  49958. this._velocityWorldLength = this._velocityWorld.length();
  49959. this._epsilon = e;
  49960. this.collisionFound = false;
  49961. };
  49962. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49963. pa.subtractToRef(point, this._tempVector);
  49964. pb.subtractToRef(point, this._tempVector2);
  49965. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49966. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49967. if (d < 0)
  49968. return false;
  49969. pc.subtractToRef(point, this._tempVector3);
  49970. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49971. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49972. if (d < 0)
  49973. return false;
  49974. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49975. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49976. return d >= 0;
  49977. };
  49978. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49979. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49980. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49981. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49982. return false;
  49983. }
  49984. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49985. return false;
  49986. return true;
  49987. };
  49988. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49989. var t0;
  49990. var embeddedInPlane = false;
  49991. //defensive programming, actually not needed.
  49992. if (!trianglePlaneArray) {
  49993. trianglePlaneArray = [];
  49994. }
  49995. if (!trianglePlaneArray[faceIndex]) {
  49996. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49997. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49998. }
  49999. var trianglePlane = trianglePlaneArray[faceIndex];
  50000. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50001. return;
  50002. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50003. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50004. if (normalDotVelocity == 0) {
  50005. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50006. return;
  50007. embeddedInPlane = true;
  50008. t0 = 0;
  50009. }
  50010. else {
  50011. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50012. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50013. if (t0 > t1) {
  50014. var temp = t1;
  50015. t1 = t0;
  50016. t0 = temp;
  50017. }
  50018. if (t0 > 1.0 || t1 < 0.0)
  50019. return;
  50020. if (t0 < 0)
  50021. t0 = 0;
  50022. if (t0 > 1.0)
  50023. t0 = 1.0;
  50024. }
  50025. this._collisionPoint.copyFromFloats(0, 0, 0);
  50026. var found = false;
  50027. var t = 1.0;
  50028. if (!embeddedInPlane) {
  50029. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50030. this._velocity.scaleToRef(t0, this._tempVector);
  50031. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50032. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50033. found = true;
  50034. t = t0;
  50035. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50036. }
  50037. }
  50038. if (!found) {
  50039. var velocitySquaredLength = this._velocity.lengthSquared();
  50040. var a = velocitySquaredLength;
  50041. this._basePoint.subtractToRef(p1, this._tempVector);
  50042. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50043. var c = this._tempVector.lengthSquared() - 1.0;
  50044. var lowestRoot = getLowestRoot(a, b, c, t);
  50045. if (lowestRoot.found) {
  50046. t = lowestRoot.root;
  50047. found = true;
  50048. this._collisionPoint.copyFrom(p1);
  50049. }
  50050. this._basePoint.subtractToRef(p2, this._tempVector);
  50051. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50052. c = this._tempVector.lengthSquared() - 1.0;
  50053. lowestRoot = getLowestRoot(a, b, c, t);
  50054. if (lowestRoot.found) {
  50055. t = lowestRoot.root;
  50056. found = true;
  50057. this._collisionPoint.copyFrom(p2);
  50058. }
  50059. this._basePoint.subtractToRef(p3, this._tempVector);
  50060. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50061. c = this._tempVector.lengthSquared() - 1.0;
  50062. lowestRoot = getLowestRoot(a, b, c, t);
  50063. if (lowestRoot.found) {
  50064. t = lowestRoot.root;
  50065. found = true;
  50066. this._collisionPoint.copyFrom(p3);
  50067. }
  50068. p2.subtractToRef(p1, this._edge);
  50069. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50070. var edgeSquaredLength = this._edge.lengthSquared();
  50071. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50072. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50073. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50074. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50075. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50076. lowestRoot = getLowestRoot(a, b, c, t);
  50077. if (lowestRoot.found) {
  50078. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50079. if (f >= 0.0 && f <= 1.0) {
  50080. t = lowestRoot.root;
  50081. found = true;
  50082. this._edge.scaleInPlace(f);
  50083. p1.addToRef(this._edge, this._collisionPoint);
  50084. }
  50085. }
  50086. p3.subtractToRef(p2, this._edge);
  50087. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50088. edgeSquaredLength = this._edge.lengthSquared();
  50089. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50090. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50091. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50092. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50093. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50094. lowestRoot = getLowestRoot(a, b, c, t);
  50095. if (lowestRoot.found) {
  50096. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50097. if (f >= 0.0 && f <= 1.0) {
  50098. t = lowestRoot.root;
  50099. found = true;
  50100. this._edge.scaleInPlace(f);
  50101. p2.addToRef(this._edge, this._collisionPoint);
  50102. }
  50103. }
  50104. p1.subtractToRef(p3, this._edge);
  50105. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50106. edgeSquaredLength = this._edge.lengthSquared();
  50107. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50108. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50109. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50110. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50111. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50112. lowestRoot = getLowestRoot(a, b, c, t);
  50113. if (lowestRoot.found) {
  50114. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50115. if (f >= 0.0 && f <= 1.0) {
  50116. t = lowestRoot.root;
  50117. found = true;
  50118. this._edge.scaleInPlace(f);
  50119. p3.addToRef(this._edge, this._collisionPoint);
  50120. }
  50121. }
  50122. }
  50123. if (found) {
  50124. var distToCollision = t * this._velocity.length();
  50125. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50126. if (!this.intersectionPoint) {
  50127. this.intersectionPoint = this._collisionPoint.clone();
  50128. }
  50129. else {
  50130. this.intersectionPoint.copyFrom(this._collisionPoint);
  50131. }
  50132. this._nearestDistance = distToCollision;
  50133. this.collisionFound = true;
  50134. }
  50135. }
  50136. };
  50137. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50138. for (var i = indexStart; i < indexEnd; i += 3) {
  50139. var p1 = pts[indices[i] - decal];
  50140. var p2 = pts[indices[i + 1] - decal];
  50141. var p3 = pts[indices[i + 2] - decal];
  50142. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50143. }
  50144. };
  50145. Collider.prototype._getResponse = function (pos, vel) {
  50146. pos.addToRef(vel, this._destinationPoint);
  50147. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50148. this._basePoint.addToRef(vel, pos);
  50149. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50150. this._slidePlaneNormal.normalize();
  50151. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50152. pos.addInPlace(this._displacementVector);
  50153. this.intersectionPoint.addInPlace(this._displacementVector);
  50154. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50155. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50156. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50157. };
  50158. return Collider;
  50159. }());
  50160. BABYLON.Collider = Collider;
  50161. })(BABYLON || (BABYLON = {}));
  50162. //# sourceMappingURL=babylon.collider.js.map
  50163. var BABYLON;
  50164. (function (BABYLON) {
  50165. //WebWorker code will be inserted to this variable.
  50166. BABYLON.CollisionWorker = "";
  50167. var WorkerTaskType;
  50168. (function (WorkerTaskType) {
  50169. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50170. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50171. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50172. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50173. var WorkerReplyType;
  50174. (function (WorkerReplyType) {
  50175. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50176. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50177. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50178. var CollisionCoordinatorWorker = /** @class */ (function () {
  50179. function CollisionCoordinatorWorker() {
  50180. var _this = this;
  50181. this._scaledPosition = BABYLON.Vector3.Zero();
  50182. this._scaledVelocity = BABYLON.Vector3.Zero();
  50183. this.onMeshUpdated = function (transformNode) {
  50184. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50185. };
  50186. this.onGeometryUpdated = function (geometry) {
  50187. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50188. };
  50189. this._afterRender = function () {
  50190. if (!_this._init)
  50191. return;
  50192. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50193. return;
  50194. }
  50195. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50196. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50197. if (_this._runningUpdated > 4) {
  50198. return;
  50199. }
  50200. ++_this._runningUpdated;
  50201. var payload = {
  50202. updatedMeshes: _this._addUpdateMeshesList,
  50203. updatedGeometries: _this._addUpdateGeometriesList,
  50204. removedGeometries: _this._toRemoveGeometryArray,
  50205. removedMeshes: _this._toRemoveMeshesArray
  50206. };
  50207. var message = {
  50208. payload: payload,
  50209. taskType: WorkerTaskType.UPDATE
  50210. };
  50211. var serializable = [];
  50212. for (var id in payload.updatedGeometries) {
  50213. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50214. //prepare transferables
  50215. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50216. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50217. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50218. }
  50219. }
  50220. _this._worker.postMessage(message, serializable);
  50221. _this._addUpdateMeshesList = {};
  50222. _this._addUpdateGeometriesList = {};
  50223. _this._toRemoveGeometryArray = [];
  50224. _this._toRemoveMeshesArray = [];
  50225. };
  50226. this._onMessageFromWorker = function (e) {
  50227. var returnData = e.data;
  50228. if (returnData.error != WorkerReplyType.SUCCESS) {
  50229. //TODO what errors can be returned from the worker?
  50230. BABYLON.Tools.Warn("error returned from worker!");
  50231. return;
  50232. }
  50233. switch (returnData.taskType) {
  50234. case WorkerTaskType.INIT:
  50235. _this._init = true;
  50236. //Update the worked with ALL of the scene's current state
  50237. _this._scene.meshes.forEach(function (mesh) {
  50238. _this.onMeshAdded(mesh);
  50239. });
  50240. _this._scene.getGeometries().forEach(function (geometry) {
  50241. _this.onGeometryAdded(geometry);
  50242. });
  50243. break;
  50244. case WorkerTaskType.UPDATE:
  50245. _this._runningUpdated--;
  50246. break;
  50247. case WorkerTaskType.COLLIDE:
  50248. var returnPayload = returnData.payload;
  50249. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50250. return;
  50251. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50252. if (callback) {
  50253. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50254. if (mesh) {
  50255. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50256. }
  50257. }
  50258. //cleanup
  50259. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50260. break;
  50261. }
  50262. };
  50263. this._collisionsCallbackArray = [];
  50264. this._init = false;
  50265. this._runningUpdated = 0;
  50266. this._addUpdateMeshesList = {};
  50267. this._addUpdateGeometriesList = {};
  50268. this._toRemoveGeometryArray = [];
  50269. this._toRemoveMeshesArray = [];
  50270. }
  50271. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50272. if (!this._init)
  50273. return;
  50274. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50275. return;
  50276. position.divideToRef(collider._radius, this._scaledPosition);
  50277. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50278. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50279. var payload = {
  50280. collider: {
  50281. position: this._scaledPosition.asArray(),
  50282. velocity: this._scaledVelocity.asArray(),
  50283. radius: collider._radius.asArray()
  50284. },
  50285. collisionId: collisionIndex,
  50286. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50287. maximumRetry: maximumRetry
  50288. };
  50289. var message = {
  50290. payload: payload,
  50291. taskType: WorkerTaskType.COLLIDE
  50292. };
  50293. this._worker.postMessage(message);
  50294. };
  50295. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50296. this._scene = scene;
  50297. this._scene.registerAfterRender(this._afterRender);
  50298. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50299. this._worker = new Worker(workerUrl);
  50300. this._worker.onmessage = this._onMessageFromWorker;
  50301. var message = {
  50302. payload: {},
  50303. taskType: WorkerTaskType.INIT
  50304. };
  50305. this._worker.postMessage(message);
  50306. };
  50307. CollisionCoordinatorWorker.prototype.destroy = function () {
  50308. this._scene.unregisterAfterRender(this._afterRender);
  50309. this._worker.terminate();
  50310. };
  50311. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50312. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50313. this.onMeshUpdated(mesh);
  50314. };
  50315. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50316. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50317. };
  50318. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50319. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50320. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50321. this.onGeometryUpdated(geometry);
  50322. };
  50323. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50324. this._toRemoveGeometryArray.push(geometry.id);
  50325. };
  50326. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50327. var submeshes = [];
  50328. if (mesh.subMeshes) {
  50329. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50330. var boundingInfo = sm.getBoundingInfo();
  50331. return {
  50332. position: idx,
  50333. verticesStart: sm.verticesStart,
  50334. verticesCount: sm.verticesCount,
  50335. indexStart: sm.indexStart,
  50336. indexCount: sm.indexCount,
  50337. hasMaterial: !!sm.getMaterial(),
  50338. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50339. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50340. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50341. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50342. };
  50343. });
  50344. }
  50345. var geometryId = null;
  50346. if (mesh instanceof BABYLON.Mesh) {
  50347. var geometry = mesh.geometry;
  50348. geometryId = geometry ? geometry.id : null;
  50349. }
  50350. else if (mesh instanceof BABYLON.InstancedMesh) {
  50351. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50352. geometryId = geometry ? geometry.id : null;
  50353. }
  50354. var boundingInfo = mesh.getBoundingInfo();
  50355. return {
  50356. uniqueId: mesh.uniqueId,
  50357. id: mesh.id,
  50358. name: mesh.name,
  50359. geometryId: geometryId,
  50360. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50361. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50362. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50363. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50364. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50365. subMeshes: submeshes,
  50366. checkCollisions: mesh.checkCollisions
  50367. };
  50368. };
  50369. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50370. return {
  50371. id: geometry.id,
  50372. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50373. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50374. indices: new Uint32Array(geometry.getIndices() || []),
  50375. };
  50376. };
  50377. return CollisionCoordinatorWorker;
  50378. }());
  50379. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50380. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50381. function CollisionCoordinatorLegacy() {
  50382. this._scaledPosition = BABYLON.Vector3.Zero();
  50383. this._scaledVelocity = BABYLON.Vector3.Zero();
  50384. this._finalPosition = BABYLON.Vector3.Zero();
  50385. }
  50386. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50387. position.divideToRef(collider._radius, this._scaledPosition);
  50388. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50389. collider.collidedMesh = null;
  50390. collider._retry = 0;
  50391. collider._initialVelocity = this._scaledVelocity;
  50392. collider._initialPosition = this._scaledPosition;
  50393. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50394. this._finalPosition.multiplyInPlace(collider._radius);
  50395. //run the callback
  50396. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50397. };
  50398. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50399. this._scene = scene;
  50400. };
  50401. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50402. //Legacy need no destruction method.
  50403. };
  50404. //No update in legacy mode
  50405. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50406. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50407. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50408. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50409. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50410. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50411. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50412. if (excludedMesh === void 0) { excludedMesh = null; }
  50413. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50414. if (collider._retry >= maximumRetry) {
  50415. finalPosition.copyFrom(position);
  50416. return;
  50417. }
  50418. // Check if this is a mesh else camera or -1
  50419. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50420. collider._initialize(position, velocity, closeDistance);
  50421. // Check all meshes
  50422. for (var index = 0; index < this._scene.meshes.length; index++) {
  50423. var mesh = this._scene.meshes[index];
  50424. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50425. mesh._checkCollision(collider);
  50426. }
  50427. }
  50428. if (!collider.collisionFound) {
  50429. position.addToRef(velocity, finalPosition);
  50430. return;
  50431. }
  50432. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50433. collider._getResponse(position, velocity);
  50434. }
  50435. if (velocity.length() <= closeDistance) {
  50436. finalPosition.copyFrom(position);
  50437. return;
  50438. }
  50439. collider._retry++;
  50440. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50441. };
  50442. return CollisionCoordinatorLegacy;
  50443. }());
  50444. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50445. })(BABYLON || (BABYLON = {}));
  50446. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50447. var BABYLON;
  50448. (function (BABYLON) {
  50449. /**
  50450. * A particle represents one of the element emitted by a particle system.
  50451. * This is mainly define by its coordinates, direction, velocity and age.
  50452. */
  50453. var Particle = /** @class */ (function () {
  50454. /**
  50455. * Creates a new instance of @see Particle
  50456. * @param particleSystem the particle system the particle belongs to
  50457. */
  50458. function Particle(particleSystem) {
  50459. this.particleSystem = particleSystem;
  50460. /**
  50461. * The world position of the particle in the scene.
  50462. */
  50463. this.position = BABYLON.Vector3.Zero();
  50464. /**
  50465. * The world direction of the particle in the scene.
  50466. */
  50467. this.direction = BABYLON.Vector3.Zero();
  50468. /**
  50469. * The color of the particle.
  50470. */
  50471. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50472. /**
  50473. * The color change of the particle per step.
  50474. */
  50475. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50476. /**
  50477. * Defines how long will the life of the particle be.
  50478. */
  50479. this.lifeTime = 1.0;
  50480. /**
  50481. * The current age of the particle.
  50482. */
  50483. this.age = 0;
  50484. /**
  50485. * The current size of the particle.
  50486. */
  50487. this.size = 0;
  50488. /**
  50489. * The current angle of the particle.
  50490. */
  50491. this.angle = 0;
  50492. /**
  50493. * Defines how fast is the angle changing.
  50494. */
  50495. this.angularSpeed = 0;
  50496. /**
  50497. * Defines the cell index used by the particle to be rendered from a sprite.
  50498. */
  50499. this.cellIndex = 0;
  50500. this._currentFrameCounter = 0;
  50501. if (!this.particleSystem.isAnimationSheetEnabled) {
  50502. return;
  50503. }
  50504. this.cellIndex = this.particleSystem.startSpriteCellID;
  50505. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50506. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50507. }
  50508. else {
  50509. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50510. }
  50511. }
  50512. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50513. // (ageOffset / scaledUpdateSpeed) / available cells
  50514. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50515. this._currentFrameCounter += scaledUpdateSpeed;
  50516. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50517. this._currentFrameCounter = 0;
  50518. this.cellIndex++;
  50519. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50520. this.cellIndex = this.particleSystem.endSpriteCellID;
  50521. }
  50522. }
  50523. };
  50524. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50525. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50526. this.cellIndex++;
  50527. this._currentFrameCounter = 0;
  50528. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50529. if (this.particleSystem.spriteCellLoop) {
  50530. this.cellIndex = this.particleSystem.startSpriteCellID;
  50531. }
  50532. else {
  50533. this.cellIndex = this.particleSystem.endSpriteCellID;
  50534. }
  50535. }
  50536. }
  50537. else {
  50538. this._currentFrameCounter++;
  50539. }
  50540. };
  50541. /**
  50542. * Copy the properties of particle to another one.
  50543. * @param other the particle to copy the information to.
  50544. */
  50545. Particle.prototype.copyTo = function (other) {
  50546. other.position.copyFrom(this.position);
  50547. other.direction.copyFrom(this.direction);
  50548. other.color.copyFrom(this.color);
  50549. other.colorStep.copyFrom(this.colorStep);
  50550. other.lifeTime = this.lifeTime;
  50551. other.age = this.age;
  50552. other.size = this.size;
  50553. other.angle = this.angle;
  50554. other.angularSpeed = this.angularSpeed;
  50555. other.particleSystem = this.particleSystem;
  50556. other.cellIndex = this.cellIndex;
  50557. };
  50558. return Particle;
  50559. }());
  50560. BABYLON.Particle = Particle;
  50561. })(BABYLON || (BABYLON = {}));
  50562. //# sourceMappingURL=babylon.particle.js.map
  50563. var BABYLON;
  50564. (function (BABYLON) {
  50565. /**
  50566. * This represents a particle system in Babylon.
  50567. * 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.
  50568. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50569. * @example https://doc.babylonjs.com/babylon101/particles
  50570. */
  50571. var ParticleSystem = /** @class */ (function () {
  50572. /**
  50573. * Instantiates a particle system.
  50574. * 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.
  50575. * @param name The name of the particle system
  50576. * @param capacity The max number of particles alive at the same time
  50577. * @param scene The scene the particle system belongs to
  50578. * @param customEffect a custom effect used to change the way particles are rendered by default
  50579. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50580. * @param epsilon Offset used to render the particles
  50581. */
  50582. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50583. if (customEffect === void 0) { customEffect = null; }
  50584. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50585. if (epsilon === void 0) { epsilon = 0.01; }
  50586. var _this = this;
  50587. /**
  50588. * List of animations used by the particle system.
  50589. */
  50590. this.animations = [];
  50591. /**
  50592. * The rendering group used by the Particle system to chose when to render.
  50593. */
  50594. this.renderingGroupId = 0;
  50595. /**
  50596. * The emitter represents the Mesh or position we are attaching the particle system to.
  50597. */
  50598. this.emitter = null;
  50599. /**
  50600. * The maximum number of particles to emit per frame
  50601. */
  50602. this.emitRate = 10;
  50603. /**
  50604. * If you want to launch only a few particles at once, that can be done, as well.
  50605. */
  50606. this.manualEmitCount = -1;
  50607. /**
  50608. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50609. */
  50610. this.updateSpeed = 0.01;
  50611. /**
  50612. * The amount of time the particle system is running (depends of the overall update speed).
  50613. */
  50614. this.targetStopDuration = 0;
  50615. /**
  50616. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50617. */
  50618. this.disposeOnStop = false;
  50619. /**
  50620. * Minimum power of emitting particles.
  50621. */
  50622. this.minEmitPower = 1;
  50623. /**
  50624. * Maximum power of emitting particles.
  50625. */
  50626. this.maxEmitPower = 1;
  50627. /**
  50628. * Minimum life time of emitting particles.
  50629. */
  50630. this.minLifeTime = 1;
  50631. /**
  50632. * Maximum life time of emitting particles.
  50633. */
  50634. this.maxLifeTime = 1;
  50635. /**
  50636. * Minimum Size of emitting particles.
  50637. */
  50638. this.minSize = 1;
  50639. /**
  50640. * Maximum Size of emitting particles.
  50641. */
  50642. this.maxSize = 1;
  50643. /**
  50644. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50645. */
  50646. this.minAngularSpeed = 0;
  50647. /**
  50648. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50649. */
  50650. this.maxAngularSpeed = 0;
  50651. /**
  50652. * The layer mask we are rendering the particles through.
  50653. */
  50654. this.layerMask = 0x0FFFFFFF;
  50655. /**
  50656. * This can help using your own shader to render the particle system.
  50657. * The according effect will be created
  50658. */
  50659. this.customShader = null;
  50660. /**
  50661. * By default particle system starts as soon as they are created. This prevents the
  50662. * automatic start to happen and let you decide when to start emitting particles.
  50663. */
  50664. this.preventAutoStart = false;
  50665. /**
  50666. * Callback triggered when the particle animation is ending.
  50667. */
  50668. this.onAnimationEnd = null;
  50669. /**
  50670. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50671. */
  50672. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50673. /**
  50674. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50675. * to override the particles.
  50676. */
  50677. this.forceDepthWrite = false;
  50678. /**
  50679. * You can use gravity if you want to give an orientation to your particles.
  50680. */
  50681. this.gravity = BABYLON.Vector3.Zero();
  50682. /**
  50683. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50684. */
  50685. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50686. /**
  50687. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50688. */
  50689. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50690. /**
  50691. * Color the particle will have at the end of its lifetime.
  50692. */
  50693. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50694. /**
  50695. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50696. */
  50697. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50698. /**
  50699. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50700. */
  50701. this.spriteCellLoop = true;
  50702. /**
  50703. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50704. */
  50705. this.spriteCellChangeSpeed = 0;
  50706. /**
  50707. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50708. */
  50709. this.startSpriteCellID = 0;
  50710. /**
  50711. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50712. */
  50713. this.endSpriteCellID = 0;
  50714. /**
  50715. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50716. */
  50717. this.spriteCellWidth = 0;
  50718. /**
  50719. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50720. */
  50721. this.spriteCellHeight = 0;
  50722. /**
  50723. * An event triggered when the system is disposed.
  50724. */
  50725. this.onDisposeObservable = new BABYLON.Observable();
  50726. this._particles = new Array();
  50727. this._stockParticles = new Array();
  50728. this._newPartsExcess = 0;
  50729. this._vertexBuffers = {};
  50730. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50731. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50732. this._scaledDirection = BABYLON.Vector3.Zero();
  50733. this._scaledGravity = BABYLON.Vector3.Zero();
  50734. this._currentRenderId = -1;
  50735. this._started = false;
  50736. this._stopped = false;
  50737. this._actualFrame = 0;
  50738. this._vertexBufferSize = 11;
  50739. this._appendParticleVertexes = null;
  50740. this.id = name;
  50741. this.name = name;
  50742. this._capacity = capacity;
  50743. this._epsilon = epsilon;
  50744. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50745. if (isAnimationSheetEnabled) {
  50746. this._vertexBufferSize = 12;
  50747. }
  50748. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50749. this._customEffect = customEffect;
  50750. scene.particleSystems.push(this);
  50751. this._createIndexBuffer();
  50752. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50753. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50754. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50755. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50756. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50757. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50758. if (this._isAnimationSheetEnabled) {
  50759. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50760. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50761. }
  50762. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50763. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50764. this._vertexBuffers["options"] = options;
  50765. // Default emitter type
  50766. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50767. this.updateFunction = function (particles) {
  50768. for (var index = 0; index < particles.length; index++) {
  50769. var particle = particles[index];
  50770. particle.age += _this._scaledUpdateSpeed;
  50771. if (particle.age >= particle.lifeTime) {
  50772. _this.recycleParticle(particle);
  50773. index--;
  50774. continue;
  50775. }
  50776. else {
  50777. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50778. particle.color.addInPlace(_this._scaledColorStep);
  50779. if (particle.color.a < 0)
  50780. particle.color.a = 0;
  50781. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50782. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50783. particle.position.addInPlace(_this._scaledDirection);
  50784. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50785. particle.direction.addInPlace(_this._scaledGravity);
  50786. if (_this._isAnimationSheetEnabled) {
  50787. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50788. }
  50789. }
  50790. }
  50791. };
  50792. }
  50793. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50794. /**
  50795. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50796. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50797. */
  50798. get: function () {
  50799. if (this.particleEmitterType.direction1) {
  50800. return this.particleEmitterType.direction1;
  50801. }
  50802. return BABYLON.Vector3.Zero();
  50803. },
  50804. set: function (value) {
  50805. if (this.particleEmitterType.direction1) {
  50806. this.particleEmitterType.direction1 = value;
  50807. }
  50808. },
  50809. enumerable: true,
  50810. configurable: true
  50811. });
  50812. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50813. /**
  50814. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50815. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50816. */
  50817. get: function () {
  50818. if (this.particleEmitterType.direction2) {
  50819. return this.particleEmitterType.direction2;
  50820. }
  50821. return BABYLON.Vector3.Zero();
  50822. },
  50823. set: function (value) {
  50824. if (this.particleEmitterType.direction2) {
  50825. this.particleEmitterType.direction2 = value;
  50826. }
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50832. /**
  50833. * 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.
  50834. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50835. */
  50836. get: function () {
  50837. if (this.particleEmitterType.minEmitBox) {
  50838. return this.particleEmitterType.minEmitBox;
  50839. }
  50840. return BABYLON.Vector3.Zero();
  50841. },
  50842. set: function (value) {
  50843. if (this.particleEmitterType.minEmitBox) {
  50844. this.particleEmitterType.minEmitBox = value;
  50845. }
  50846. },
  50847. enumerable: true,
  50848. configurable: true
  50849. });
  50850. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50851. /**
  50852. * 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.
  50853. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50854. */
  50855. get: function () {
  50856. if (this.particleEmitterType.maxEmitBox) {
  50857. return this.particleEmitterType.maxEmitBox;
  50858. }
  50859. return BABYLON.Vector3.Zero();
  50860. },
  50861. set: function (value) {
  50862. if (this.particleEmitterType.maxEmitBox) {
  50863. this.particleEmitterType.maxEmitBox = value;
  50864. }
  50865. },
  50866. enumerable: true,
  50867. configurable: true
  50868. });
  50869. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50870. /**
  50871. * Sets a callback that will be triggered when the system is disposed.
  50872. */
  50873. set: function (callback) {
  50874. if (this._onDisposeObserver) {
  50875. this.onDisposeObservable.remove(this._onDisposeObserver);
  50876. }
  50877. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50878. },
  50879. enumerable: true,
  50880. configurable: true
  50881. });
  50882. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50883. /**
  50884. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50885. */
  50886. get: function () {
  50887. return this._isAnimationSheetEnabled;
  50888. },
  50889. enumerable: true,
  50890. configurable: true
  50891. });
  50892. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50893. /**
  50894. * Gets the current list of active particles
  50895. */
  50896. get: function () {
  50897. return this._particles;
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. /**
  50903. * Returns the string "ParticleSystem"
  50904. * @returns a string containing the class name
  50905. */
  50906. ParticleSystem.prototype.getClassName = function () {
  50907. return "ParticleSystem";
  50908. };
  50909. ParticleSystem.prototype._createIndexBuffer = function () {
  50910. var indices = [];
  50911. var index = 0;
  50912. for (var count = 0; count < this._capacity; count++) {
  50913. indices.push(index);
  50914. indices.push(index + 1);
  50915. indices.push(index + 2);
  50916. indices.push(index);
  50917. indices.push(index + 2);
  50918. indices.push(index + 3);
  50919. index += 4;
  50920. }
  50921. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50922. };
  50923. /**
  50924. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50925. * Its lifetime will start back at 0.
  50926. * @param particle The particle to recycle
  50927. */
  50928. ParticleSystem.prototype.recycleParticle = function (particle) {
  50929. var lastParticle = this._particles.pop();
  50930. if (lastParticle !== particle) {
  50931. lastParticle.copyTo(particle);
  50932. this._stockParticles.push(lastParticle);
  50933. }
  50934. };
  50935. /**
  50936. * Gets the maximum number of particles active at the same time.
  50937. * @returns The max number of active particles.
  50938. */
  50939. ParticleSystem.prototype.getCapacity = function () {
  50940. return this._capacity;
  50941. };
  50942. /**
  50943. * Gets Wether there are still active particles in the system.
  50944. * @returns True if it is alive, otherwise false.
  50945. */
  50946. ParticleSystem.prototype.isAlive = function () {
  50947. return this._alive;
  50948. };
  50949. /**
  50950. * Gets Wether the system has been started.
  50951. * @returns True if it has been started, otherwise false.
  50952. */
  50953. ParticleSystem.prototype.isStarted = function () {
  50954. return this._started;
  50955. };
  50956. /**
  50957. * Starts the particle system and begins to emit.
  50958. */
  50959. ParticleSystem.prototype.start = function () {
  50960. this._started = true;
  50961. this._stopped = false;
  50962. this._actualFrame = 0;
  50963. };
  50964. /**
  50965. * Stops the particle system.
  50966. */
  50967. ParticleSystem.prototype.stop = function () {
  50968. this._stopped = true;
  50969. };
  50970. /**
  50971. * Remove all active particles
  50972. */
  50973. ParticleSystem.prototype.reset = function () {
  50974. this._stockParticles = [];
  50975. this._particles = [];
  50976. };
  50977. /**
  50978. * @ignore (for internal use only)
  50979. */
  50980. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50981. var offset = index * this._vertexBufferSize;
  50982. this._vertexData[offset] = particle.position.x;
  50983. this._vertexData[offset + 1] = particle.position.y;
  50984. this._vertexData[offset + 2] = particle.position.z;
  50985. this._vertexData[offset + 3] = particle.color.r;
  50986. this._vertexData[offset + 4] = particle.color.g;
  50987. this._vertexData[offset + 5] = particle.color.b;
  50988. this._vertexData[offset + 6] = particle.color.a;
  50989. this._vertexData[offset + 7] = particle.angle;
  50990. this._vertexData[offset + 8] = particle.size;
  50991. this._vertexData[offset + 9] = offsetX;
  50992. this._vertexData[offset + 10] = offsetY;
  50993. };
  50994. /**
  50995. * @ignore (for internal use only)
  50996. */
  50997. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50998. if (offsetX === 0)
  50999. offsetX = this._epsilon;
  51000. else if (offsetX === 1)
  51001. offsetX = 1 - this._epsilon;
  51002. if (offsetY === 0)
  51003. offsetY = this._epsilon;
  51004. else if (offsetY === 1)
  51005. offsetY = 1 - this._epsilon;
  51006. var offset = index * this._vertexBufferSize;
  51007. this._vertexData[offset] = particle.position.x;
  51008. this._vertexData[offset + 1] = particle.position.y;
  51009. this._vertexData[offset + 2] = particle.position.z;
  51010. this._vertexData[offset + 3] = particle.color.r;
  51011. this._vertexData[offset + 4] = particle.color.g;
  51012. this._vertexData[offset + 5] = particle.color.b;
  51013. this._vertexData[offset + 6] = particle.color.a;
  51014. this._vertexData[offset + 7] = particle.angle;
  51015. this._vertexData[offset + 8] = particle.size;
  51016. this._vertexData[offset + 9] = offsetX;
  51017. this._vertexData[offset + 10] = offsetY;
  51018. this._vertexData[offset + 11] = particle.cellIndex;
  51019. };
  51020. ParticleSystem.prototype._update = function (newParticles) {
  51021. // Update current
  51022. this._alive = this._particles.length > 0;
  51023. this.updateFunction(this._particles);
  51024. // Add new ones
  51025. var worldMatrix;
  51026. if (this.emitter.position) {
  51027. var emitterMesh = this.emitter;
  51028. worldMatrix = emitterMesh.getWorldMatrix();
  51029. }
  51030. else {
  51031. var emitterPosition = this.emitter;
  51032. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51033. }
  51034. var particle;
  51035. for (var index = 0; index < newParticles; index++) {
  51036. if (this._particles.length === this._capacity) {
  51037. break;
  51038. }
  51039. if (this._stockParticles.length !== 0) {
  51040. particle = this._stockParticles.pop();
  51041. particle.age = 0;
  51042. particle.cellIndex = this.startSpriteCellID;
  51043. }
  51044. else {
  51045. particle = new BABYLON.Particle(this);
  51046. }
  51047. this._particles.push(particle);
  51048. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51049. if (this.startPositionFunction) {
  51050. this.startPositionFunction(worldMatrix, particle.position, particle);
  51051. }
  51052. else {
  51053. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51054. }
  51055. if (this.startDirectionFunction) {
  51056. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51057. }
  51058. else {
  51059. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51060. }
  51061. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51062. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51063. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51064. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51065. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51066. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51067. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51068. }
  51069. };
  51070. ParticleSystem.prototype._getEffect = function () {
  51071. if (this._customEffect) {
  51072. return this._customEffect;
  51073. }
  51074. ;
  51075. var defines = [];
  51076. if (this._scene.clipPlane) {
  51077. defines.push("#define CLIPPLANE");
  51078. }
  51079. if (this._isAnimationSheetEnabled) {
  51080. defines.push("#define ANIMATESHEET");
  51081. }
  51082. // Effect
  51083. var join = defines.join("\n");
  51084. if (this._cachedDefines !== join) {
  51085. this._cachedDefines = join;
  51086. var attributesNamesOrOptions;
  51087. var effectCreationOption;
  51088. if (this._isAnimationSheetEnabled) {
  51089. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51090. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51091. }
  51092. else {
  51093. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51094. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51095. }
  51096. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51097. }
  51098. return this._effect;
  51099. };
  51100. /**
  51101. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51102. */
  51103. ParticleSystem.prototype.animate = function () {
  51104. if (!this._started)
  51105. return;
  51106. var effect = this._getEffect();
  51107. // Check
  51108. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51109. return;
  51110. if (this._currentRenderId === this._scene.getRenderId()) {
  51111. return;
  51112. }
  51113. this._currentRenderId = this._scene.getRenderId();
  51114. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51115. // determine the number of particles we need to create
  51116. var newParticles;
  51117. if (this.manualEmitCount > -1) {
  51118. newParticles = this.manualEmitCount;
  51119. this._newPartsExcess = 0;
  51120. this.manualEmitCount = 0;
  51121. }
  51122. else {
  51123. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51124. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51125. }
  51126. if (this._newPartsExcess > 1.0) {
  51127. newParticles += this._newPartsExcess >> 0;
  51128. this._newPartsExcess -= this._newPartsExcess >> 0;
  51129. }
  51130. this._alive = false;
  51131. if (!this._stopped) {
  51132. this._actualFrame += this._scaledUpdateSpeed;
  51133. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51134. this.stop();
  51135. }
  51136. else {
  51137. newParticles = 0;
  51138. }
  51139. this._update(newParticles);
  51140. // Stopped?
  51141. if (this._stopped) {
  51142. if (!this._alive) {
  51143. this._started = false;
  51144. if (this.onAnimationEnd) {
  51145. this.onAnimationEnd();
  51146. }
  51147. if (this.disposeOnStop) {
  51148. this._scene._toBeDisposed.push(this);
  51149. }
  51150. }
  51151. }
  51152. // Animation sheet
  51153. if (this._isAnimationSheetEnabled) {
  51154. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51155. }
  51156. else {
  51157. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51158. }
  51159. // Update VBO
  51160. var offset = 0;
  51161. for (var index = 0; index < this._particles.length; index++) {
  51162. var particle = this._particles[index];
  51163. this._appendParticleVertexes(offset, particle);
  51164. offset += 4;
  51165. }
  51166. if (this._vertexBuffer) {
  51167. this._vertexBuffer.update(this._vertexData);
  51168. }
  51169. };
  51170. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51171. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51172. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51173. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51174. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51175. };
  51176. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51177. this._appendParticleVertex(offset++, particle, 0, 0);
  51178. this._appendParticleVertex(offset++, particle, 1, 0);
  51179. this._appendParticleVertex(offset++, particle, 1, 1);
  51180. this._appendParticleVertex(offset++, particle, 0, 1);
  51181. };
  51182. /**
  51183. * Rebuilds the particle system.
  51184. */
  51185. ParticleSystem.prototype.rebuild = function () {
  51186. this._createIndexBuffer();
  51187. if (this._vertexBuffer) {
  51188. this._vertexBuffer._rebuild();
  51189. }
  51190. };
  51191. /**
  51192. * Renders the particle system in its current state.
  51193. * @returns the current number of particles
  51194. */
  51195. ParticleSystem.prototype.render = function () {
  51196. var effect = this._getEffect();
  51197. // Check
  51198. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51199. return 0;
  51200. }
  51201. var engine = this._scene.getEngine();
  51202. // Render
  51203. engine.enableEffect(effect);
  51204. engine.setState(false);
  51205. var viewMatrix = this._scene.getViewMatrix();
  51206. effect.setTexture("diffuseSampler", this.particleTexture);
  51207. effect.setMatrix("view", viewMatrix);
  51208. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51209. if (this._isAnimationSheetEnabled) {
  51210. var baseSize = this.particleTexture.getBaseSize();
  51211. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51212. }
  51213. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51214. if (this._scene.clipPlane) {
  51215. var clipPlane = this._scene.clipPlane;
  51216. var invView = viewMatrix.clone();
  51217. invView.invert();
  51218. effect.setMatrix("invView", invView);
  51219. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51220. }
  51221. // VBOs
  51222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51223. // Draw order
  51224. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51225. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51226. }
  51227. else {
  51228. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51229. }
  51230. if (this.forceDepthWrite) {
  51231. engine.setDepthWrite(true);
  51232. }
  51233. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51235. return this._particles.length;
  51236. };
  51237. /**
  51238. * Disposes the particle system and free the associated resources
  51239. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51240. */
  51241. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51242. if (disposeTexture === void 0) { disposeTexture = true; }
  51243. if (this._vertexBuffer) {
  51244. this._vertexBuffer.dispose();
  51245. this._vertexBuffer = null;
  51246. }
  51247. if (this._indexBuffer) {
  51248. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51249. this._indexBuffer = null;
  51250. }
  51251. if (disposeTexture && this.particleTexture) {
  51252. this.particleTexture.dispose();
  51253. this.particleTexture = null;
  51254. }
  51255. // Remove from scene
  51256. var index = this._scene.particleSystems.indexOf(this);
  51257. if (index > -1) {
  51258. this._scene.particleSystems.splice(index, 1);
  51259. }
  51260. // Callback
  51261. this.onDisposeObservable.notifyObservers(this);
  51262. this.onDisposeObservable.clear();
  51263. };
  51264. /**
  51265. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51266. * @param radius The radius of the sphere to emit from
  51267. * @returns the emitter
  51268. */
  51269. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51270. if (radius === void 0) { radius = 1; }
  51271. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51272. this.particleEmitterType = particleEmitter;
  51273. return particleEmitter;
  51274. };
  51275. /**
  51276. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51277. * @param radius The radius of the sphere to emit from
  51278. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51279. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51280. * @returns the emitter
  51281. */
  51282. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51283. if (radius === void 0) { radius = 1; }
  51284. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51285. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51286. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51287. this.particleEmitterType = particleEmitter;
  51288. return particleEmitter;
  51289. };
  51290. /**
  51291. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51292. * @param radius The radius of the cone to emit from
  51293. * @param angle The base angle of the cone
  51294. * @returns the emitter
  51295. */
  51296. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51297. if (radius === void 0) { radius = 1; }
  51298. if (angle === void 0) { angle = Math.PI / 4; }
  51299. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51300. this.particleEmitterType = particleEmitter;
  51301. return particleEmitter;
  51302. };
  51303. // 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.
  51304. /**
  51305. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51306. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51307. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51308. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51309. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51310. * @returns the emitter
  51311. */
  51312. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51313. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51314. this.direction1 = direction1;
  51315. this.direction2 = direction2;
  51316. this.minEmitBox = minEmitBox;
  51317. this.maxEmitBox = maxEmitBox;
  51318. this.particleEmitterType = particleEmitter;
  51319. return particleEmitter;
  51320. };
  51321. /**
  51322. * Clones the particle system.
  51323. * @param name The name of the cloned object
  51324. * @param newEmitter The new emitter to use
  51325. * @returns the cloned particle system
  51326. */
  51327. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51328. var custom = null;
  51329. var program = null;
  51330. if (this.customShader != null) {
  51331. program = this.customShader;
  51332. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51333. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51334. }
  51335. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51336. result.customShader = program;
  51337. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51338. if (newEmitter === undefined) {
  51339. newEmitter = this.emitter;
  51340. }
  51341. result.emitter = newEmitter;
  51342. if (this.particleTexture) {
  51343. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51344. }
  51345. if (!this.preventAutoStart) {
  51346. result.start();
  51347. }
  51348. return result;
  51349. };
  51350. /**
  51351. * Serializes the particle system to a JSON object.
  51352. * @returns the JSON object
  51353. */
  51354. ParticleSystem.prototype.serialize = function () {
  51355. var serializationObject = {};
  51356. serializationObject.name = this.name;
  51357. serializationObject.id = this.id;
  51358. // Emitter
  51359. if (this.emitter.position) {
  51360. var emitterMesh = this.emitter;
  51361. serializationObject.emitterId = emitterMesh.id;
  51362. }
  51363. else {
  51364. var emitterPosition = this.emitter;
  51365. serializationObject.emitter = emitterPosition.asArray();
  51366. }
  51367. serializationObject.capacity = this.getCapacity();
  51368. if (this.particleTexture) {
  51369. serializationObject.textureName = this.particleTexture.name;
  51370. }
  51371. // Animations
  51372. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51373. // Particle system
  51374. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51375. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51376. serializationObject.minSize = this.minSize;
  51377. serializationObject.maxSize = this.maxSize;
  51378. serializationObject.minEmitPower = this.minEmitPower;
  51379. serializationObject.maxEmitPower = this.maxEmitPower;
  51380. serializationObject.minLifeTime = this.minLifeTime;
  51381. serializationObject.maxLifeTime = this.maxLifeTime;
  51382. serializationObject.emitRate = this.emitRate;
  51383. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51384. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51385. serializationObject.gravity = this.gravity.asArray();
  51386. serializationObject.direction1 = this.direction1.asArray();
  51387. serializationObject.direction2 = this.direction2.asArray();
  51388. serializationObject.color1 = this.color1.asArray();
  51389. serializationObject.color2 = this.color2.asArray();
  51390. serializationObject.colorDead = this.colorDead.asArray();
  51391. serializationObject.updateSpeed = this.updateSpeed;
  51392. serializationObject.targetStopDuration = this.targetStopDuration;
  51393. serializationObject.textureMask = this.textureMask.asArray();
  51394. serializationObject.blendMode = this.blendMode;
  51395. serializationObject.customShader = this.customShader;
  51396. serializationObject.preventAutoStart = this.preventAutoStart;
  51397. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51398. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51399. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51400. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51401. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51402. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51403. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51404. // Emitter
  51405. if (this.particleEmitterType) {
  51406. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51407. }
  51408. return serializationObject;
  51409. };
  51410. /**
  51411. * Parses a JSON object to create a particle system.
  51412. * @param parsedParticleSystem The JSON object to parse
  51413. * @param scene The scene to create the particle system in
  51414. * @param rootUrl The root url to use to load external dependencies like texture
  51415. * @returns the Parsed particle system
  51416. */
  51417. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51418. var name = parsedParticleSystem.name;
  51419. var custom = null;
  51420. var program = null;
  51421. if (parsedParticleSystem.customShader) {
  51422. program = parsedParticleSystem.customShader;
  51423. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51424. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51425. }
  51426. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51427. particleSystem.customShader = program;
  51428. if (parsedParticleSystem.id) {
  51429. particleSystem.id = parsedParticleSystem.id;
  51430. }
  51431. // Auto start
  51432. if (parsedParticleSystem.preventAutoStart) {
  51433. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51434. }
  51435. // Texture
  51436. if (parsedParticleSystem.textureName) {
  51437. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51438. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51439. }
  51440. // Emitter
  51441. if (parsedParticleSystem.emitterId) {
  51442. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51443. }
  51444. else {
  51445. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51446. }
  51447. // Animations
  51448. if (parsedParticleSystem.animations) {
  51449. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51450. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51451. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51452. }
  51453. }
  51454. if (parsedParticleSystem.autoAnimate) {
  51455. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51456. }
  51457. // Particle system
  51458. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51459. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51460. particleSystem.minSize = parsedParticleSystem.minSize;
  51461. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51462. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51463. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51464. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51465. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51466. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51467. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51468. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51469. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51470. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51471. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51472. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51473. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51474. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51475. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51476. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51477. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51478. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51479. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51480. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51481. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51482. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51483. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51484. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51485. if (!particleSystem.preventAutoStart) {
  51486. particleSystem.start();
  51487. }
  51488. return particleSystem;
  51489. };
  51490. /**
  51491. * Source color is added to the destination color without alpha affecting the result.
  51492. */
  51493. ParticleSystem.BLENDMODE_ONEONE = 0;
  51494. /**
  51495. * Blend current color and particle color using particle’s alpha.
  51496. */
  51497. ParticleSystem.BLENDMODE_STANDARD = 1;
  51498. return ParticleSystem;
  51499. }());
  51500. BABYLON.ParticleSystem = ParticleSystem;
  51501. })(BABYLON || (BABYLON = {}));
  51502. //# sourceMappingURL=babylon.particleSystem.js.map
  51503. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51504. var BABYLON;
  51505. (function (BABYLON) {
  51506. /**
  51507. * Particle emitter emitting particles from the inside of a box.
  51508. * It emits the particles randomly between 2 given directions.
  51509. */
  51510. var BoxParticleEmitter = /** @class */ (function () {
  51511. /**
  51512. * Creates a new instance of @see BoxParticleEmitter
  51513. */
  51514. function BoxParticleEmitter() {
  51515. /**
  51516. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51517. */
  51518. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51519. /**
  51520. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51521. */
  51522. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51523. /**
  51524. * 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.
  51525. */
  51526. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51527. /**
  51528. * 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.
  51529. */
  51530. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51531. }
  51532. /**
  51533. * Called by the particle System when the direction is computed for the created particle.
  51534. * @param emitPower is the power of the particle (speed)
  51535. * @param worldMatrix is the world matrix of the particle system
  51536. * @param directionToUpdate is the direction vector to update with the result
  51537. * @param particle is the particle we are computed the direction for
  51538. */
  51539. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51540. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51541. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51542. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51543. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51544. };
  51545. /**
  51546. * Called by the particle System when the position is computed for the created particle.
  51547. * @param worldMatrix is the world matrix of the particle system
  51548. * @param positionToUpdate is the position vector to update with the result
  51549. * @param particle is the particle we are computed the position for
  51550. */
  51551. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51552. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51553. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51554. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51556. };
  51557. /**
  51558. * Clones the current emitter and returns a copy of it
  51559. * @returns the new emitter
  51560. */
  51561. BoxParticleEmitter.prototype.clone = function () {
  51562. var newOne = new BoxParticleEmitter();
  51563. BABYLON.Tools.DeepCopy(this, newOne);
  51564. return newOne;
  51565. };
  51566. /**
  51567. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51568. * @param effect defines the update shader
  51569. */
  51570. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51571. effect.setVector3("direction1", this.direction1);
  51572. effect.setVector3("direction2", this.direction2);
  51573. effect.setVector3("minEmitBox", this.minEmitBox);
  51574. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51575. };
  51576. /**
  51577. * Returns a string to use to update the GPU particles update shader
  51578. * @returns a string containng the defines string
  51579. */
  51580. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51581. return "#define BOXEMITTER";
  51582. };
  51583. /**
  51584. * Returns the string "BoxEmitter"
  51585. * @returns a string containing the class name
  51586. */
  51587. BoxParticleEmitter.prototype.getClassName = function () {
  51588. return "BoxEmitter";
  51589. };
  51590. /**
  51591. * Serializes the particle system to a JSON object.
  51592. * @returns the JSON object
  51593. */
  51594. BoxParticleEmitter.prototype.serialize = function () {
  51595. var serializationObject = {};
  51596. serializationObject.type = this.getClassName();
  51597. serializationObject.direction1 = this.direction1.asArray();
  51598. ;
  51599. serializationObject.direction2 = this.direction2.asArray();
  51600. ;
  51601. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51602. ;
  51603. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51604. ;
  51605. return serializationObject;
  51606. };
  51607. /**
  51608. * Parse properties from a JSON object
  51609. * @param serializationObject defines the JSON object
  51610. */
  51611. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51612. this.direction1.copyFrom(serializationObject.direction1);
  51613. this.direction2.copyFrom(serializationObject.direction2);
  51614. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51615. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51616. };
  51617. return BoxParticleEmitter;
  51618. }());
  51619. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51620. })(BABYLON || (BABYLON = {}));
  51621. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51622. var BABYLON;
  51623. (function (BABYLON) {
  51624. /**
  51625. * Particle emitter emitting particles from the inside of a cone.
  51626. * It emits the particles alongside the cone volume from the base to the particle.
  51627. * The emission direction might be randomized.
  51628. */
  51629. var ConeParticleEmitter = /** @class */ (function () {
  51630. /**
  51631. * Creates a new instance of @see ConeParticleEmitter
  51632. * @param radius the radius of the emission cone (1 by default)
  51633. * @param angles the cone base angle (PI by default)
  51634. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51635. */
  51636. function ConeParticleEmitter(radius,
  51637. /**
  51638. * The radius of the emission cone.
  51639. */
  51640. angle,
  51641. /**
  51642. * The cone base angle.
  51643. */
  51644. directionRandomizer) {
  51645. if (radius === void 0) { radius = 1; }
  51646. if (angle === void 0) { angle = Math.PI; }
  51647. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51648. this.angle = angle;
  51649. this.directionRandomizer = directionRandomizer;
  51650. this.radius = radius;
  51651. }
  51652. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51653. /**
  51654. * Gets the radius of the emission cone.
  51655. */
  51656. get: function () {
  51657. return this._radius;
  51658. },
  51659. /**
  51660. * Sets the radius of the emission cone.
  51661. */
  51662. set: function (value) {
  51663. this._radius = value;
  51664. if (this.angle !== 0) {
  51665. this._height = value / Math.tan(this.angle / 2);
  51666. }
  51667. else {
  51668. this._height = 1;
  51669. }
  51670. },
  51671. enumerable: true,
  51672. configurable: true
  51673. });
  51674. /**
  51675. * Called by the particle System when the direction is computed for the created particle.
  51676. * @param emitPower is the power of the particle (speed)
  51677. * @param worldMatrix is the world matrix of the particle system
  51678. * @param directionToUpdate is the direction vector to update with the result
  51679. * @param particle is the particle we are computed the direction for
  51680. */
  51681. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51682. if (this.angle === 0) {
  51683. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51684. }
  51685. else {
  51686. // measure the direction Vector from the emitter to the particle.
  51687. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51688. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51689. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51690. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51691. direction.x += randX;
  51692. direction.y += randY;
  51693. direction.z += randZ;
  51694. direction.normalize();
  51695. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51696. }
  51697. };
  51698. /**
  51699. * Called by the particle System when the position is computed for the created particle.
  51700. * @param worldMatrix is the world matrix of the particle system
  51701. * @param positionToUpdate is the position vector to update with the result
  51702. * @param particle is the particle we are computed the position for
  51703. */
  51704. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51705. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51706. var h = BABYLON.Scalar.RandomRange(0, 1);
  51707. // Better distribution in a cone at normal angles.
  51708. h = 1 - h * h;
  51709. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51710. radius = radius * h / this._height;
  51711. var randX = radius * Math.sin(s);
  51712. var randZ = radius * Math.cos(s);
  51713. var randY = h * this._height;
  51714. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51715. };
  51716. /**
  51717. * Clones the current emitter and returns a copy of it
  51718. * @returns the new emitter
  51719. */
  51720. ConeParticleEmitter.prototype.clone = function () {
  51721. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51722. BABYLON.Tools.DeepCopy(this, newOne);
  51723. return newOne;
  51724. };
  51725. /**
  51726. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51727. * @param effect defines the update shader
  51728. */
  51729. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51730. effect.setFloat("radius", this.radius);
  51731. effect.setFloat("angle", this.angle);
  51732. effect.setFloat("height", this._height);
  51733. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51734. };
  51735. /**
  51736. * Returns a string to use to update the GPU particles update shader
  51737. * @returns a string containng the defines string
  51738. */
  51739. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51740. return "#define CONEEMITTER";
  51741. };
  51742. /**
  51743. * Returns the string "BoxEmitter"
  51744. * @returns a string containing the class name
  51745. */
  51746. ConeParticleEmitter.prototype.getClassName = function () {
  51747. return "ConeEmitter";
  51748. };
  51749. /**
  51750. * Serializes the particle system to a JSON object.
  51751. * @returns the JSON object
  51752. */
  51753. ConeParticleEmitter.prototype.serialize = function () {
  51754. var serializationObject = {};
  51755. serializationObject.type = this.getClassName();
  51756. serializationObject.radius = this.radius;
  51757. serializationObject.angle = this.angle;
  51758. serializationObject.directionRandomizer = this.directionRandomizer;
  51759. return serializationObject;
  51760. };
  51761. /**
  51762. * Parse properties from a JSON object
  51763. * @param serializationObject defines the JSON object
  51764. */
  51765. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51766. this.radius = serializationObject.radius;
  51767. this.angle = serializationObject.angle;
  51768. this.directionRandomizer = serializationObject.directionRandomizer;
  51769. };
  51770. return ConeParticleEmitter;
  51771. }());
  51772. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51773. })(BABYLON || (BABYLON = {}));
  51774. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51775. var BABYLON;
  51776. (function (BABYLON) {
  51777. /**
  51778. * Particle emitter emitting particles from the inside of a sphere.
  51779. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51780. */
  51781. var SphereParticleEmitter = /** @class */ (function () {
  51782. /**
  51783. * Creates a new instance of @see SphereParticleEmitter
  51784. * @param radius the radius of the emission sphere (1 by default)
  51785. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51786. */
  51787. function SphereParticleEmitter(
  51788. /**
  51789. * The radius of the emission sphere.
  51790. */
  51791. radius,
  51792. /**
  51793. * How much to randomize the particle direction [0-1].
  51794. */
  51795. directionRandomizer) {
  51796. if (radius === void 0) { radius = 1; }
  51797. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51798. this.radius = radius;
  51799. this.directionRandomizer = directionRandomizer;
  51800. }
  51801. /**
  51802. * Called by the particle System when the direction is computed for the created particle.
  51803. * @param emitPower is the power of the particle (speed)
  51804. * @param worldMatrix is the world matrix of the particle system
  51805. * @param directionToUpdate is the direction vector to update with the result
  51806. * @param particle is the particle we are computed the direction for
  51807. */
  51808. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51809. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51810. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51811. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51812. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51813. direction.x += randX;
  51814. direction.y += randY;
  51815. direction.z += randZ;
  51816. direction.normalize();
  51817. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51818. };
  51819. /**
  51820. * Called by the particle System when the position is computed for the created particle.
  51821. * @param worldMatrix is the world matrix of the particle system
  51822. * @param positionToUpdate is the position vector to update with the result
  51823. * @param particle is the particle we are computed the position for
  51824. */
  51825. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51826. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51827. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51828. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51829. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51830. var randY = randRadius * Math.cos(theta);
  51831. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51832. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51833. };
  51834. /**
  51835. * Clones the current emitter and returns a copy of it
  51836. * @returns the new emitter
  51837. */
  51838. SphereParticleEmitter.prototype.clone = function () {
  51839. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51840. BABYLON.Tools.DeepCopy(this, newOne);
  51841. return newOne;
  51842. };
  51843. /**
  51844. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51845. * @param effect defines the update shader
  51846. */
  51847. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51848. effect.setFloat("radius", this.radius);
  51849. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51850. };
  51851. /**
  51852. * Returns a string to use to update the GPU particles update shader
  51853. * @returns a string containng the defines string
  51854. */
  51855. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51856. return "#define SPHEREEMITTER";
  51857. };
  51858. /**
  51859. * Returns the string "SphereParticleEmitter"
  51860. * @returns a string containing the class name
  51861. */
  51862. SphereParticleEmitter.prototype.getClassName = function () {
  51863. return "SphereParticleEmitter";
  51864. };
  51865. /**
  51866. * Serializes the particle system to a JSON object.
  51867. * @returns the JSON object
  51868. */
  51869. SphereParticleEmitter.prototype.serialize = function () {
  51870. var serializationObject = {};
  51871. serializationObject.type = this.getClassName();
  51872. serializationObject.radius = this.radius;
  51873. serializationObject.directionRandomizer = this.directionRandomizer;
  51874. return serializationObject;
  51875. };
  51876. /**
  51877. * Parse properties from a JSON object
  51878. * @param serializationObject defines the JSON object
  51879. */
  51880. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51881. this.radius = serializationObject.radius;
  51882. this.directionRandomizer = serializationObject.directionRandomizer;
  51883. };
  51884. return SphereParticleEmitter;
  51885. }());
  51886. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51887. /**
  51888. * Particle emitter emitting particles from the inside of a sphere.
  51889. * It emits the particles randomly between two vectors.
  51890. */
  51891. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51892. __extends(SphereDirectedParticleEmitter, _super);
  51893. /**
  51894. * Creates a new instance of @see SphereDirectedParticleEmitter
  51895. * @param radius the radius of the emission sphere (1 by default)
  51896. * @param direction1 the min limit of the emission direction (up vector by default)
  51897. * @param direction2 the max limit of the emission direction (up vector by default)
  51898. */
  51899. function SphereDirectedParticleEmitter(radius,
  51900. /**
  51901. * The min limit of the emission direction.
  51902. */
  51903. direction1,
  51904. /**
  51905. * The max limit of the emission direction.
  51906. */
  51907. direction2) {
  51908. if (radius === void 0) { radius = 1; }
  51909. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51910. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51911. var _this = _super.call(this, radius) || this;
  51912. _this.direction1 = direction1;
  51913. _this.direction2 = direction2;
  51914. return _this;
  51915. }
  51916. /**
  51917. * Called by the particle System when the direction is computed for the created particle.
  51918. * @param emitPower is the power of the particle (speed)
  51919. * @param worldMatrix is the world matrix of the particle system
  51920. * @param directionToUpdate is the direction vector to update with the result
  51921. * @param particle is the particle we are computed the direction for
  51922. */
  51923. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51924. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51925. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51926. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51927. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51928. };
  51929. /**
  51930. * Clones the current emitter and returns a copy of it
  51931. * @returns the new emitter
  51932. */
  51933. SphereDirectedParticleEmitter.prototype.clone = function () {
  51934. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51935. BABYLON.Tools.DeepCopy(this, newOne);
  51936. return newOne;
  51937. };
  51938. /**
  51939. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51940. * @param effect defines the update shader
  51941. */
  51942. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51943. effect.setFloat("radius", this.radius);
  51944. effect.setVector3("direction1", this.direction1);
  51945. effect.setVector3("direction2", this.direction2);
  51946. };
  51947. /**
  51948. * Returns a string to use to update the GPU particles update shader
  51949. * @returns a string containng the defines string
  51950. */
  51951. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51952. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51953. };
  51954. /**
  51955. * Returns the string "SphereDirectedParticleEmitter"
  51956. * @returns a string containing the class name
  51957. */
  51958. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51959. return "SphereDirectedParticleEmitter";
  51960. };
  51961. /**
  51962. * Serializes the particle system to a JSON object.
  51963. * @returns the JSON object
  51964. */
  51965. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51966. var serializationObject = _super.prototype.serialize.call(this);
  51967. ;
  51968. serializationObject.direction1 = this.direction1.asArray();
  51969. ;
  51970. serializationObject.direction2 = this.direction2.asArray();
  51971. ;
  51972. return serializationObject;
  51973. };
  51974. /**
  51975. * Parse properties from a JSON object
  51976. * @param serializationObject defines the JSON object
  51977. */
  51978. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51979. _super.prototype.parse.call(this, serializationObject);
  51980. this.direction1.copyFrom(serializationObject.direction1);
  51981. this.direction2.copyFrom(serializationObject.direction2);
  51982. };
  51983. return SphereDirectedParticleEmitter;
  51984. }(SphereParticleEmitter));
  51985. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51986. })(BABYLON || (BABYLON = {}));
  51987. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51988. var BABYLON;
  51989. (function (BABYLON) {
  51990. /**
  51991. * Represents one particle of a solid particle system.
  51992. * @see SolidParticleSystem
  51993. */
  51994. var SolidParticle = /** @class */ (function () {
  51995. /**
  51996. * Creates a Solid Particle object.
  51997. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51998. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51999. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52000. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52001. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52002. * @param shapeId (integer) is the model shape identifier in the SPS.
  52003. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52004. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52005. */
  52006. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52007. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52008. /**
  52009. * particle global index
  52010. */
  52011. this.idx = 0;
  52012. /**
  52013. * The color of the particle
  52014. */
  52015. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52016. /**
  52017. * The world space position of the particle.
  52018. */
  52019. this.position = BABYLON.Vector3.Zero();
  52020. /**
  52021. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52022. */
  52023. this.rotation = BABYLON.Vector3.Zero();
  52024. /**
  52025. * The scaling of the particle.
  52026. */
  52027. this.scaling = BABYLON.Vector3.One();
  52028. /**
  52029. * The uvs of the particle.
  52030. */
  52031. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52032. /**
  52033. * The current speed of the particle.
  52034. */
  52035. this.velocity = BABYLON.Vector3.Zero();
  52036. /**
  52037. * The pivot point in the particle local space.
  52038. */
  52039. this.pivot = BABYLON.Vector3.Zero();
  52040. /**
  52041. * Must the particle be translated from its pivot point in its local space ?
  52042. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52043. * Default : false
  52044. */
  52045. this.translateFromPivot = false;
  52046. /**
  52047. * Is the particle active or not ?
  52048. */
  52049. this.alive = true;
  52050. /**
  52051. * Is the particle visible or not ?
  52052. */
  52053. this.isVisible = true;
  52054. /**
  52055. * Index of this particle in the global "positions" array (Internal use)
  52056. */
  52057. this._pos = 0;
  52058. /**
  52059. * Index of this particle in the global "indices" array (Internal use)
  52060. */
  52061. this._ind = 0;
  52062. /**
  52063. * ModelShape id of this particle
  52064. */
  52065. this.shapeId = 0;
  52066. /**
  52067. * Index of the particle in its shape id (Internal use)
  52068. */
  52069. this.idxInShape = 0;
  52070. /**
  52071. * Still set as invisible in order to skip useless computations (Internal use)
  52072. */
  52073. this._stillInvisible = false;
  52074. /**
  52075. * Last computed particle rotation matrix
  52076. */
  52077. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52078. /**
  52079. * Parent particle Id, if any.
  52080. * Default null.
  52081. */
  52082. this.parentId = null;
  52083. /**
  52084. * Internal global position in the SPS.
  52085. */
  52086. this._globalPosition = BABYLON.Vector3.Zero();
  52087. this.idx = particleIndex;
  52088. this._pos = positionIndex;
  52089. this._ind = indiceIndex;
  52090. this._model = model;
  52091. this.shapeId = shapeId;
  52092. this.idxInShape = idxInShape;
  52093. this._sps = sps;
  52094. if (modelBoundingInfo) {
  52095. this._modelBoundingInfo = modelBoundingInfo;
  52096. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52097. }
  52098. }
  52099. Object.defineProperty(SolidParticle.prototype, "scale", {
  52100. /**
  52101. * Legacy support, changed scale to scaling
  52102. */
  52103. get: function () {
  52104. return this.scaling;
  52105. },
  52106. /**
  52107. * Legacy support, changed scale to scaling
  52108. */
  52109. set: function (scale) {
  52110. this.scaling = scale;
  52111. },
  52112. enumerable: true,
  52113. configurable: true
  52114. });
  52115. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52116. /**
  52117. * Legacy support, changed quaternion to rotationQuaternion
  52118. */
  52119. get: function () {
  52120. return this.rotationQuaternion;
  52121. },
  52122. /**
  52123. * Legacy support, changed quaternion to rotationQuaternion
  52124. */
  52125. set: function (q) {
  52126. this.rotationQuaternion = q;
  52127. },
  52128. enumerable: true,
  52129. configurable: true
  52130. });
  52131. /**
  52132. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52133. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52134. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52135. * @returns true if it intersects
  52136. */
  52137. SolidParticle.prototype.intersectsMesh = function (target) {
  52138. if (!this._boundingInfo || !target._boundingInfo) {
  52139. return false;
  52140. }
  52141. if (this._sps._bSphereOnly) {
  52142. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52143. }
  52144. return this._boundingInfo.intersects(target._boundingInfo, false);
  52145. };
  52146. return SolidParticle;
  52147. }());
  52148. BABYLON.SolidParticle = SolidParticle;
  52149. /**
  52150. * Represents the shape of the model used by one particle of a solid particle system.
  52151. * SPS internal tool, don't use it manually.
  52152. * @see SolidParticleSystem
  52153. */
  52154. var ModelShape = /** @class */ (function () {
  52155. /**
  52156. * 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.
  52157. * SPS internal tool, don't use it manually.
  52158. * @ignore
  52159. */
  52160. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52161. /**
  52162. * length of the shape in the model indices array (internal use)
  52163. */
  52164. this._indicesLength = 0;
  52165. this.shapeID = id;
  52166. this._shape = shape;
  52167. this._indicesLength = indicesLength;
  52168. this._shapeUV = shapeUV;
  52169. this._positionFunction = posFunction;
  52170. this._vertexFunction = vtxFunction;
  52171. }
  52172. return ModelShape;
  52173. }());
  52174. BABYLON.ModelShape = ModelShape;
  52175. /**
  52176. * Represents a Depth Sorted Particle in the solid particle system.
  52177. * @see SolidParticleSystem
  52178. */
  52179. var DepthSortedParticle = /** @class */ (function () {
  52180. function DepthSortedParticle() {
  52181. /**
  52182. * Index of the particle in the "indices" array
  52183. */
  52184. this.ind = 0;
  52185. /**
  52186. * Length of the particle shape in the "indices" array
  52187. */
  52188. this.indicesLength = 0;
  52189. /**
  52190. * Squared distance from the particle to the camera
  52191. */
  52192. this.sqDistance = 0.0;
  52193. }
  52194. return DepthSortedParticle;
  52195. }());
  52196. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52197. })(BABYLON || (BABYLON = {}));
  52198. //# sourceMappingURL=babylon.solidParticle.js.map
  52199. var BABYLON;
  52200. (function (BABYLON) {
  52201. /**
  52202. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52203. *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.
  52204. * The SPS is also a particle system. It provides some methods to manage the particles.
  52205. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52206. *
  52207. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52208. */
  52209. var SolidParticleSystem = /** @class */ (function () {
  52210. /**
  52211. * Creates a SPS (Solid Particle System) object.
  52212. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52213. * @param scene (Scene) is the scene in which the SPS is added.
  52214. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52215. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52216. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52217. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52218. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52219. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52220. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52221. */
  52222. function SolidParticleSystem(name, scene, options) {
  52223. /**
  52224. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52225. * Example : var p = SPS.particles[i];
  52226. */
  52227. this.particles = new Array();
  52228. /**
  52229. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52230. */
  52231. this.nbParticles = 0;
  52232. /**
  52233. * If the particles must ever face the camera (default false). Useful for planar particles.
  52234. */
  52235. this.billboard = false;
  52236. /**
  52237. * Recompute normals when adding a shape
  52238. */
  52239. this.recomputeNormals = true;
  52240. /**
  52241. * This a counter ofr your own usage. It's not set by any SPS functions.
  52242. */
  52243. this.counter = 0;
  52244. /**
  52245. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52246. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52247. */
  52248. this.vars = {};
  52249. /**
  52250. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52251. */
  52252. this._bSphereOnly = false;
  52253. /**
  52254. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52255. */
  52256. this._bSphereRadiusFactor = 1.0;
  52257. this._positions = new Array();
  52258. this._indices = new Array();
  52259. this._normals = new Array();
  52260. this._colors = new Array();
  52261. this._uvs = new Array();
  52262. this._index = 0; // indices index
  52263. this._updatable = true;
  52264. this._pickable = false;
  52265. this._isVisibilityBoxLocked = false;
  52266. this._alwaysVisible = false;
  52267. this._depthSort = false;
  52268. this._shapeCounter = 0;
  52269. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52270. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52271. this._computeParticleColor = true;
  52272. this._computeParticleTexture = true;
  52273. this._computeParticleRotation = true;
  52274. this._computeParticleVertex = false;
  52275. this._computeBoundingBox = false;
  52276. this._depthSortParticles = true;
  52277. this._cam_axisZ = BABYLON.Vector3.Zero();
  52278. this._cam_axisY = BABYLON.Vector3.Zero();
  52279. this._cam_axisX = BABYLON.Vector3.Zero();
  52280. this._axisZ = BABYLON.Axis.Z;
  52281. this._camDir = BABYLON.Vector3.Zero();
  52282. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52283. this._rotMatrix = new BABYLON.Matrix();
  52284. this._invertMatrix = new BABYLON.Matrix();
  52285. this._rotated = BABYLON.Vector3.Zero();
  52286. this._quaternion = new BABYLON.Quaternion();
  52287. this._vertex = BABYLON.Vector3.Zero();
  52288. this._normal = BABYLON.Vector3.Zero();
  52289. this._yaw = 0.0;
  52290. this._pitch = 0.0;
  52291. this._roll = 0.0;
  52292. this._halfroll = 0.0;
  52293. this._halfpitch = 0.0;
  52294. this._halfyaw = 0.0;
  52295. this._sinRoll = 0.0;
  52296. this._cosRoll = 0.0;
  52297. this._sinPitch = 0.0;
  52298. this._cosPitch = 0.0;
  52299. this._sinYaw = 0.0;
  52300. this._cosYaw = 0.0;
  52301. this._mustUnrotateFixedNormals = false;
  52302. this._minimum = BABYLON.Vector3.Zero();
  52303. this._maximum = BABYLON.Vector3.Zero();
  52304. this._minBbox = BABYLON.Vector3.Zero();
  52305. this._maxBbox = BABYLON.Vector3.Zero();
  52306. this._particlesIntersect = false;
  52307. this._depthSortFunction = function (p1, p2) {
  52308. return (p2.sqDistance - p1.sqDistance);
  52309. };
  52310. this._needs32Bits = false;
  52311. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52312. this._scaledPivot = BABYLON.Vector3.Zero();
  52313. this._particleHasParent = false;
  52314. this.name = name;
  52315. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52316. this._camera = scene.activeCamera;
  52317. this._pickable = options ? options.isPickable : false;
  52318. this._depthSort = options ? options.enableDepthSort : false;
  52319. this._particlesIntersect = options ? options.particleIntersection : false;
  52320. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52321. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52322. if (options && options.updatable) {
  52323. this._updatable = options.updatable;
  52324. }
  52325. else {
  52326. this._updatable = true;
  52327. }
  52328. if (this._pickable) {
  52329. this.pickedParticles = [];
  52330. }
  52331. if (this._depthSort) {
  52332. this.depthSortedParticles = [];
  52333. }
  52334. }
  52335. /**
  52336. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52337. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52338. * @returns the created mesh
  52339. */
  52340. SolidParticleSystem.prototype.buildMesh = function () {
  52341. if (this.nbParticles === 0) {
  52342. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52343. this.addShape(triangle, 1);
  52344. triangle.dispose();
  52345. }
  52346. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52347. this._positions32 = new Float32Array(this._positions);
  52348. this._uvs32 = new Float32Array(this._uvs);
  52349. this._colors32 = new Float32Array(this._colors);
  52350. if (this.recomputeNormals) {
  52351. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52352. }
  52353. this._normals32 = new Float32Array(this._normals);
  52354. this._fixedNormal32 = new Float32Array(this._normals);
  52355. if (this._mustUnrotateFixedNormals) {
  52356. this._unrotateFixedNormals();
  52357. }
  52358. var vertexData = new BABYLON.VertexData();
  52359. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52360. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52361. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52362. if (this._uvs32) {
  52363. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52364. ;
  52365. }
  52366. if (this._colors32) {
  52367. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52368. }
  52369. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52370. vertexData.applyToMesh(mesh, this._updatable);
  52371. this.mesh = mesh;
  52372. this.mesh.isPickable = this._pickable;
  52373. // free memory
  52374. if (!this._depthSort) {
  52375. this._indices = null;
  52376. }
  52377. this._positions = null;
  52378. this._normals = null;
  52379. this._uvs = null;
  52380. this._colors = null;
  52381. if (!this._updatable) {
  52382. this.particles.length = 0;
  52383. }
  52384. return mesh;
  52385. };
  52386. /**
  52387. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52388. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52389. * Thus the particles generated from `digest()` have their property `position` set yet.
  52390. * @param mesh ( Mesh ) is the mesh to be digested
  52391. * @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
  52392. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52393. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52394. * @returns the current SPS
  52395. */
  52396. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52397. var size = (options && options.facetNb) || 1;
  52398. var number = (options && options.number) || 0;
  52399. var delta = (options && options.delta) || 0;
  52400. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52401. var meshInd = mesh.getIndices();
  52402. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52403. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52404. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52405. var f = 0; // facet counter
  52406. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52407. // compute size from number
  52408. if (number) {
  52409. number = (number > totalFacets) ? totalFacets : number;
  52410. size = Math.round(totalFacets / number);
  52411. delta = 0;
  52412. }
  52413. else {
  52414. size = (size > totalFacets) ? totalFacets : size;
  52415. }
  52416. var facetPos = []; // submesh positions
  52417. var facetInd = []; // submesh indices
  52418. var facetUV = []; // submesh UV
  52419. var facetCol = []; // submesh colors
  52420. var barycenter = BABYLON.Vector3.Zero();
  52421. var sizeO = size;
  52422. while (f < totalFacets) {
  52423. size = sizeO + Math.floor((1 + delta) * Math.random());
  52424. if (f > totalFacets - size) {
  52425. size = totalFacets - f;
  52426. }
  52427. // reset temp arrays
  52428. facetPos.length = 0;
  52429. facetInd.length = 0;
  52430. facetUV.length = 0;
  52431. facetCol.length = 0;
  52432. // iterate over "size" facets
  52433. var fi = 0;
  52434. for (var j = f * 3; j < (f + size) * 3; j++) {
  52435. facetInd.push(fi);
  52436. var i = meshInd[j];
  52437. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52438. if (meshUV) {
  52439. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52440. }
  52441. if (meshCol) {
  52442. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52443. }
  52444. fi++;
  52445. }
  52446. // create a model shape for each single particle
  52447. var idx = this.nbParticles;
  52448. var shape = this._posToShape(facetPos);
  52449. var shapeUV = this._uvsToShapeUV(facetUV);
  52450. // compute the barycenter of the shape
  52451. var v;
  52452. for (v = 0; v < shape.length; v++) {
  52453. barycenter.addInPlace(shape[v]);
  52454. }
  52455. barycenter.scaleInPlace(1 / shape.length);
  52456. // shift the shape from its barycenter to the origin
  52457. for (v = 0; v < shape.length; v++) {
  52458. shape[v].subtractInPlace(barycenter);
  52459. }
  52460. var bInfo;
  52461. if (this._particlesIntersect) {
  52462. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52463. }
  52464. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52465. // add the particle in the SPS
  52466. var currentPos = this._positions.length;
  52467. var currentInd = this._indices.length;
  52468. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52469. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52470. // initialize the particle position
  52471. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52472. this._index += shape.length;
  52473. idx++;
  52474. this.nbParticles++;
  52475. this._shapeCounter++;
  52476. f += size;
  52477. }
  52478. return this;
  52479. };
  52480. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52481. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52482. var index = 0;
  52483. var idx = 0;
  52484. for (var p = 0; p < this.particles.length; p++) {
  52485. this._particle = this.particles[p];
  52486. this._shape = this._particle._model._shape;
  52487. if (this._particle.rotationQuaternion) {
  52488. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52489. }
  52490. else {
  52491. this._yaw = this._particle.rotation.y;
  52492. this._pitch = this._particle.rotation.x;
  52493. this._roll = this._particle.rotation.z;
  52494. this._quaternionRotationYPR();
  52495. }
  52496. this._quaternionToRotationMatrix();
  52497. this._rotMatrix.invertToRef(this._invertMatrix);
  52498. for (var pt = 0; pt < this._shape.length; pt++) {
  52499. idx = index + pt * 3;
  52500. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52501. this._fixedNormal32[idx] = this._normal.x;
  52502. this._fixedNormal32[idx + 1] = this._normal.y;
  52503. this._fixedNormal32[idx + 2] = this._normal.z;
  52504. }
  52505. index = idx + 3;
  52506. }
  52507. };
  52508. //reset copy
  52509. SolidParticleSystem.prototype._resetCopy = function () {
  52510. this._copy.position.x = 0;
  52511. this._copy.position.y = 0;
  52512. this._copy.position.z = 0;
  52513. this._copy.rotation.x = 0;
  52514. this._copy.rotation.y = 0;
  52515. this._copy.rotation.z = 0;
  52516. this._copy.rotationQuaternion = null;
  52517. this._copy.scaling.x = 1.0;
  52518. this._copy.scaling.y = 1.0;
  52519. this._copy.scaling.z = 1.0;
  52520. this._copy.uvs.x = 0;
  52521. this._copy.uvs.y = 0;
  52522. this._copy.uvs.z = 1.0;
  52523. this._copy.uvs.w = 1.0;
  52524. this._copy.color = null;
  52525. this._copy.translateFromPivot = false;
  52526. };
  52527. // _meshBuilder : inserts the shape model in the global SPS mesh
  52528. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52529. var i;
  52530. var u = 0;
  52531. var c = 0;
  52532. var n = 0;
  52533. this._resetCopy();
  52534. if (options && options.positionFunction) {
  52535. options.positionFunction(this._copy, idx, idxInShape);
  52536. this._mustUnrotateFixedNormals = true;
  52537. }
  52538. if (this._copy.rotationQuaternion) {
  52539. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52540. }
  52541. else {
  52542. this._yaw = this._copy.rotation.y;
  52543. this._pitch = this._copy.rotation.x;
  52544. this._roll = this._copy.rotation.z;
  52545. this._quaternionRotationYPR();
  52546. }
  52547. this._quaternionToRotationMatrix();
  52548. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52549. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52550. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52551. if (this._copy.translateFromPivot) {
  52552. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52553. }
  52554. else {
  52555. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52556. }
  52557. for (i = 0; i < shape.length; i++) {
  52558. this._vertex.x = shape[i].x;
  52559. this._vertex.y = shape[i].y;
  52560. this._vertex.z = shape[i].z;
  52561. if (options && options.vertexFunction) {
  52562. options.vertexFunction(this._copy, this._vertex, i);
  52563. }
  52564. this._vertex.x *= this._copy.scaling.x;
  52565. this._vertex.y *= this._copy.scaling.y;
  52566. this._vertex.z *= this._copy.scaling.z;
  52567. this._vertex.x -= this._scaledPivot.x;
  52568. this._vertex.y -= this._scaledPivot.y;
  52569. this._vertex.z -= this._scaledPivot.z;
  52570. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52571. this._rotated.addInPlace(this._pivotBackTranslation);
  52572. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52573. if (meshUV) {
  52574. 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);
  52575. u += 2;
  52576. }
  52577. if (this._copy.color) {
  52578. this._color = this._copy.color;
  52579. }
  52580. else if (meshCol && meshCol[c] !== undefined) {
  52581. this._color.r = meshCol[c];
  52582. this._color.g = meshCol[c + 1];
  52583. this._color.b = meshCol[c + 2];
  52584. this._color.a = meshCol[c + 3];
  52585. }
  52586. else {
  52587. this._color.r = 1.0;
  52588. this._color.g = 1.0;
  52589. this._color.b = 1.0;
  52590. this._color.a = 1.0;
  52591. }
  52592. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52593. c += 4;
  52594. if (!this.recomputeNormals && meshNor) {
  52595. this._normal.x = meshNor[n];
  52596. this._normal.y = meshNor[n + 1];
  52597. this._normal.z = meshNor[n + 2];
  52598. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52599. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52600. n += 3;
  52601. }
  52602. }
  52603. for (i = 0; i < meshInd.length; i++) {
  52604. var current_ind = p + meshInd[i];
  52605. indices.push(current_ind);
  52606. if (current_ind > 65535) {
  52607. this._needs32Bits = true;
  52608. }
  52609. }
  52610. if (this._pickable) {
  52611. var nbfaces = meshInd.length / 3;
  52612. for (i = 0; i < nbfaces; i++) {
  52613. this.pickedParticles.push({ idx: idx, faceId: i });
  52614. }
  52615. }
  52616. if (this._depthSort) {
  52617. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52618. }
  52619. return this._copy;
  52620. };
  52621. // returns a shape array from positions array
  52622. SolidParticleSystem.prototype._posToShape = function (positions) {
  52623. var shape = [];
  52624. for (var i = 0; i < positions.length; i += 3) {
  52625. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52626. }
  52627. return shape;
  52628. };
  52629. // returns a shapeUV array from a Vector4 uvs
  52630. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52631. var shapeUV = [];
  52632. if (uvs) {
  52633. for (var i = 0; i < uvs.length; i++)
  52634. shapeUV.push(uvs[i]);
  52635. }
  52636. return shapeUV;
  52637. };
  52638. // adds a new particle object in the particles array
  52639. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52640. if (bInfo === void 0) { bInfo = null; }
  52641. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52642. this.particles.push(sp);
  52643. return sp;
  52644. };
  52645. /**
  52646. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52647. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52648. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52649. * @param nb (positive integer) the number of particles to be created from this model
  52650. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52651. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52652. * @returns the number of shapes in the system
  52653. */
  52654. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52655. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52656. var meshInd = mesh.getIndices();
  52657. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52658. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52659. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52660. var bbInfo;
  52661. if (this._particlesIntersect) {
  52662. bbInfo = mesh.getBoundingInfo();
  52663. }
  52664. var shape = this._posToShape(meshPos);
  52665. var shapeUV = this._uvsToShapeUV(meshUV);
  52666. var posfunc = options ? options.positionFunction : null;
  52667. var vtxfunc = options ? options.vertexFunction : null;
  52668. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52669. // particles
  52670. var sp;
  52671. var currentCopy;
  52672. var idx = this.nbParticles;
  52673. for (var i = 0; i < nb; i++) {
  52674. var currentPos = this._positions.length;
  52675. var currentInd = this._indices.length;
  52676. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52677. if (this._updatable) {
  52678. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52679. sp.position.copyFrom(currentCopy.position);
  52680. sp.rotation.copyFrom(currentCopy.rotation);
  52681. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52682. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52683. }
  52684. if (currentCopy.color && sp.color) {
  52685. sp.color.copyFrom(currentCopy.color);
  52686. }
  52687. sp.scaling.copyFrom(currentCopy.scaling);
  52688. sp.uvs.copyFrom(currentCopy.uvs);
  52689. }
  52690. this._index += shape.length;
  52691. idx++;
  52692. }
  52693. this.nbParticles += nb;
  52694. this._shapeCounter++;
  52695. return this._shapeCounter - 1;
  52696. };
  52697. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52698. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52699. this._resetCopy();
  52700. if (particle._model._positionFunction) {
  52701. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52702. }
  52703. if (this._copy.rotationQuaternion) {
  52704. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52705. }
  52706. else {
  52707. this._yaw = this._copy.rotation.y;
  52708. this._pitch = this._copy.rotation.x;
  52709. this._roll = this._copy.rotation.z;
  52710. this._quaternionRotationYPR();
  52711. }
  52712. this._quaternionToRotationMatrix();
  52713. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52714. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52715. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52716. if (this._copy.translateFromPivot) {
  52717. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52718. }
  52719. else {
  52720. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52721. }
  52722. this._shape = particle._model._shape;
  52723. for (var pt = 0; pt < this._shape.length; pt++) {
  52724. this._vertex.x = this._shape[pt].x;
  52725. this._vertex.y = this._shape[pt].y;
  52726. this._vertex.z = this._shape[pt].z;
  52727. if (particle._model._vertexFunction) {
  52728. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52729. }
  52730. this._vertex.x *= this._copy.scaling.x;
  52731. this._vertex.y *= this._copy.scaling.y;
  52732. this._vertex.z *= this._copy.scaling.z;
  52733. this._vertex.x -= this._scaledPivot.x;
  52734. this._vertex.y -= this._scaledPivot.y;
  52735. this._vertex.z -= this._scaledPivot.z;
  52736. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52737. this._rotated.addInPlace(this._pivotBackTranslation);
  52738. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52739. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52740. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52741. }
  52742. particle.position.x = 0.0;
  52743. particle.position.y = 0.0;
  52744. particle.position.z = 0.0;
  52745. particle.rotation.x = 0.0;
  52746. particle.rotation.y = 0.0;
  52747. particle.rotation.z = 0.0;
  52748. particle.rotationQuaternion = null;
  52749. particle.scaling.x = 1.0;
  52750. particle.scaling.y = 1.0;
  52751. particle.scaling.z = 1.0;
  52752. particle.uvs.x = 0.0;
  52753. particle.uvs.y = 0.0;
  52754. particle.uvs.z = 1.0;
  52755. particle.uvs.w = 1.0;
  52756. particle.pivot.x = 0.0;
  52757. particle.pivot.y = 0.0;
  52758. particle.pivot.z = 0.0;
  52759. particle.translateFromPivot = false;
  52760. particle.parentId = null;
  52761. };
  52762. /**
  52763. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52764. * @returns the SPS.
  52765. */
  52766. SolidParticleSystem.prototype.rebuildMesh = function () {
  52767. for (var p = 0; p < this.particles.length; p++) {
  52768. this._rebuildParticle(this.particles[p]);
  52769. }
  52770. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52771. return this;
  52772. };
  52773. /**
  52774. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52775. * This method calls `updateParticle()` for each particle of the SPS.
  52776. * For an animated SPS, it is usually called within the render loop.
  52777. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52778. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52779. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52780. * @returns the SPS.
  52781. */
  52782. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52783. if (start === void 0) { start = 0; }
  52784. if (end === void 0) { end = this.nbParticles - 1; }
  52785. if (update === void 0) { update = true; }
  52786. if (!this._updatable) {
  52787. return this;
  52788. }
  52789. // custom beforeUpdate
  52790. this.beforeUpdateParticles(start, end, update);
  52791. this._cam_axisX.x = 1.0;
  52792. this._cam_axisX.y = 0.0;
  52793. this._cam_axisX.z = 0.0;
  52794. this._cam_axisY.x = 0.0;
  52795. this._cam_axisY.y = 1.0;
  52796. this._cam_axisY.z = 0.0;
  52797. this._cam_axisZ.x = 0.0;
  52798. this._cam_axisZ.y = 0.0;
  52799. this._cam_axisZ.z = 1.0;
  52800. // cases when the World Matrix is to be computed first
  52801. if (this.billboard || this._depthSort) {
  52802. this.mesh.computeWorldMatrix(true);
  52803. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52804. }
  52805. // if the particles will always face the camera
  52806. if (this.billboard) {
  52807. // compute the camera position and un-rotate it by the current mesh rotation
  52808. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52809. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52810. this._cam_axisZ.normalize();
  52811. // same for camera up vector extracted from the cam view matrix
  52812. var view = this._camera.getViewMatrix(true);
  52813. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52814. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52815. this._cam_axisY.normalize();
  52816. this._cam_axisX.normalize();
  52817. }
  52818. // if depthSort, compute the camera global position in the mesh local system
  52819. if (this._depthSort) {
  52820. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52821. }
  52822. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52823. var idx = 0; // current position index in the global array positions32
  52824. var index = 0; // position start index in the global array positions32 of the current particle
  52825. var colidx = 0; // current color index in the global array colors32
  52826. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52827. var uvidx = 0; // current uv index in the global array uvs32
  52828. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52829. var pt = 0; // current index in the particle model shape
  52830. if (this.mesh.isFacetDataEnabled) {
  52831. this._computeBoundingBox = true;
  52832. }
  52833. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52834. if (this._computeBoundingBox) {
  52835. if (start == 0 && end == this.nbParticles - 1) {
  52836. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52837. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52838. }
  52839. else {
  52840. if (this.mesh._boundingInfo) {
  52841. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52842. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52843. }
  52844. }
  52845. }
  52846. // particle loop
  52847. index = this.particles[start]._pos;
  52848. var vpos = (index / 3) | 0;
  52849. colorIndex = vpos * 4;
  52850. uvIndex = vpos * 2;
  52851. for (var p = start; p <= end; p++) {
  52852. this._particle = this.particles[p];
  52853. this._shape = this._particle._model._shape;
  52854. this._shapeUV = this._particle._model._shapeUV;
  52855. // call to custom user function to update the particle properties
  52856. this.updateParticle(this._particle);
  52857. // camera-particle distance for depth sorting
  52858. if (this._depthSort && this._depthSortParticles) {
  52859. var dsp = this.depthSortedParticles[p];
  52860. dsp.ind = this._particle._ind;
  52861. dsp.indicesLength = this._particle._model._indicesLength;
  52862. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52863. }
  52864. // skip the computations for inactive or already invisible particles
  52865. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52866. // increment indexes for the next particle
  52867. pt = this._shape.length;
  52868. index += pt * 3;
  52869. colorIndex += pt * 4;
  52870. uvIndex += pt * 2;
  52871. continue;
  52872. }
  52873. if (this._particle.isVisible) {
  52874. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52875. this._particleHasParent = (this._particle.parentId !== null);
  52876. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52877. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52878. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52879. // particle rotation matrix
  52880. if (this.billboard) {
  52881. this._particle.rotation.x = 0.0;
  52882. this._particle.rotation.y = 0.0;
  52883. }
  52884. if (this._computeParticleRotation || this.billboard) {
  52885. if (this._particle.rotationQuaternion) {
  52886. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52887. }
  52888. else {
  52889. this._yaw = this._particle.rotation.y;
  52890. this._pitch = this._particle.rotation.x;
  52891. this._roll = this._particle.rotation.z;
  52892. this._quaternionRotationYPR();
  52893. }
  52894. this._quaternionToRotationMatrix();
  52895. }
  52896. if (this._particleHasParent) {
  52897. this._parent = this.particles[this._particle.parentId];
  52898. 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];
  52899. 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];
  52900. 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];
  52901. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52902. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52903. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52904. if (this._computeParticleRotation || this.billboard) {
  52905. 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];
  52906. 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];
  52907. 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];
  52908. 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];
  52909. 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];
  52910. 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];
  52911. 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];
  52912. 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];
  52913. 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];
  52914. }
  52915. }
  52916. else {
  52917. this._particle._globalPosition.x = this._particle.position.x;
  52918. this._particle._globalPosition.y = this._particle.position.y;
  52919. this._particle._globalPosition.z = this._particle.position.z;
  52920. if (this._computeParticleRotation || this.billboard) {
  52921. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52922. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52923. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52924. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52925. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52926. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52927. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52928. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52929. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52930. }
  52931. }
  52932. if (this._particle.translateFromPivot) {
  52933. this._pivotBackTranslation.x = 0.0;
  52934. this._pivotBackTranslation.y = 0.0;
  52935. this._pivotBackTranslation.z = 0.0;
  52936. }
  52937. else {
  52938. this._pivotBackTranslation.x = this._scaledPivot.x;
  52939. this._pivotBackTranslation.y = this._scaledPivot.y;
  52940. this._pivotBackTranslation.z = this._scaledPivot.z;
  52941. }
  52942. // particle vertex loop
  52943. for (pt = 0; pt < this._shape.length; pt++) {
  52944. idx = index + pt * 3;
  52945. colidx = colorIndex + pt * 4;
  52946. uvidx = uvIndex + pt * 2;
  52947. this._vertex.x = this._shape[pt].x;
  52948. this._vertex.y = this._shape[pt].y;
  52949. this._vertex.z = this._shape[pt].z;
  52950. if (this._computeParticleVertex) {
  52951. this.updateParticleVertex(this._particle, this._vertex, pt);
  52952. }
  52953. // positions
  52954. this._vertex.x *= this._particle.scaling.x;
  52955. this._vertex.y *= this._particle.scaling.y;
  52956. this._vertex.z *= this._particle.scaling.z;
  52957. this._vertex.x -= this._scaledPivot.x;
  52958. this._vertex.y -= this._scaledPivot.y;
  52959. this._vertex.z -= this._scaledPivot.z;
  52960. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52961. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52962. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52963. this._rotated.x += this._pivotBackTranslation.x;
  52964. this._rotated.y += this._pivotBackTranslation.y;
  52965. this._rotated.z += this._pivotBackTranslation.z;
  52966. 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;
  52967. 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;
  52968. 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;
  52969. if (this._computeBoundingBox) {
  52970. if (this._positions32[idx] < this._minimum.x) {
  52971. this._minimum.x = this._positions32[idx];
  52972. }
  52973. if (this._positions32[idx] > this._maximum.x) {
  52974. this._maximum.x = this._positions32[idx];
  52975. }
  52976. if (this._positions32[idx + 1] < this._minimum.y) {
  52977. this._minimum.y = this._positions32[idx + 1];
  52978. }
  52979. if (this._positions32[idx + 1] > this._maximum.y) {
  52980. this._maximum.y = this._positions32[idx + 1];
  52981. }
  52982. if (this._positions32[idx + 2] < this._minimum.z) {
  52983. this._minimum.z = this._positions32[idx + 2];
  52984. }
  52985. if (this._positions32[idx + 2] > this._maximum.z) {
  52986. this._maximum.z = this._positions32[idx + 2];
  52987. }
  52988. }
  52989. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52990. if (!this._computeParticleVertex) {
  52991. this._normal.x = this._fixedNormal32[idx];
  52992. this._normal.y = this._fixedNormal32[idx + 1];
  52993. this._normal.z = this._fixedNormal32[idx + 2];
  52994. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52995. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52996. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52997. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52998. 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;
  52999. 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;
  53000. }
  53001. if (this._computeParticleColor && this._particle.color) {
  53002. this._colors32[colidx] = this._particle.color.r;
  53003. this._colors32[colidx + 1] = this._particle.color.g;
  53004. this._colors32[colidx + 2] = this._particle.color.b;
  53005. this._colors32[colidx + 3] = this._particle.color.a;
  53006. }
  53007. if (this._computeParticleTexture) {
  53008. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53009. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53010. }
  53011. }
  53012. }
  53013. else {
  53014. this._particle._stillInvisible = true; // mark the particle as invisible
  53015. for (pt = 0; pt < this._shape.length; pt++) {
  53016. idx = index + pt * 3;
  53017. colidx = colorIndex + pt * 4;
  53018. uvidx = uvIndex + pt * 2;
  53019. this._positions32[idx] = 0.0;
  53020. this._positions32[idx + 1] = 0.0;
  53021. this._positions32[idx + 2] = 0.0;
  53022. this._normals32[idx] = 0.0;
  53023. this._normals32[idx + 1] = 0.0;
  53024. this._normals32[idx + 2] = 0.0;
  53025. if (this._computeParticleColor && this._particle.color) {
  53026. this._colors32[colidx] = this._particle.color.r;
  53027. this._colors32[colidx + 1] = this._particle.color.g;
  53028. this._colors32[colidx + 2] = this._particle.color.b;
  53029. this._colors32[colidx + 3] = this._particle.color.a;
  53030. }
  53031. if (this._computeParticleTexture) {
  53032. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53033. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53034. }
  53035. }
  53036. }
  53037. // if the particle intersections must be computed : update the bbInfo
  53038. if (this._particlesIntersect) {
  53039. var bInfo = this._particle._boundingInfo;
  53040. var bBox = bInfo.boundingBox;
  53041. var bSphere = bInfo.boundingSphere;
  53042. if (!this._bSphereOnly) {
  53043. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53044. for (var b = 0; b < bBox.vectors.length; b++) {
  53045. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53046. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53047. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53048. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53049. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53050. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53051. 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;
  53052. 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;
  53053. 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;
  53054. }
  53055. bBox._update(this.mesh._worldMatrix);
  53056. }
  53057. // place and scale the particle bouding sphere in the SPS local system, then update it
  53058. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53059. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53060. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53061. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53062. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53063. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53064. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53065. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53066. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53067. 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));
  53068. bSphere._update(this.mesh._worldMatrix);
  53069. }
  53070. // increment indexes for the next particle
  53071. index = idx + 3;
  53072. colorIndex = colidx + 4;
  53073. uvIndex = uvidx + 2;
  53074. }
  53075. // if the VBO must be updated
  53076. if (update) {
  53077. if (this._computeParticleColor) {
  53078. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53079. }
  53080. if (this._computeParticleTexture) {
  53081. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53082. }
  53083. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53084. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53085. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53086. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53087. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53088. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53089. for (var i = 0; i < this._normals32.length; i++) {
  53090. this._fixedNormal32[i] = this._normals32[i];
  53091. }
  53092. }
  53093. if (!this.mesh.areNormalsFrozen) {
  53094. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53095. }
  53096. }
  53097. if (this._depthSort && this._depthSortParticles) {
  53098. this.depthSortedParticles.sort(this._depthSortFunction);
  53099. var dspl = this.depthSortedParticles.length;
  53100. var sorted = 0;
  53101. var lind = 0;
  53102. var sind = 0;
  53103. var sid = 0;
  53104. for (sorted = 0; sorted < dspl; sorted++) {
  53105. lind = this.depthSortedParticles[sorted].indicesLength;
  53106. sind = this.depthSortedParticles[sorted].ind;
  53107. for (var i = 0; i < lind; i++) {
  53108. this._indices32[sid] = this._indices[sind + i];
  53109. sid++;
  53110. }
  53111. }
  53112. this.mesh.updateIndices(this._indices32);
  53113. }
  53114. }
  53115. if (this._computeBoundingBox) {
  53116. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53117. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53118. }
  53119. this.afterUpdateParticles(start, end, update);
  53120. return this;
  53121. };
  53122. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53123. this._halfroll = this._roll * 0.5;
  53124. this._halfpitch = this._pitch * 0.5;
  53125. this._halfyaw = this._yaw * 0.5;
  53126. this._sinRoll = Math.sin(this._halfroll);
  53127. this._cosRoll = Math.cos(this._halfroll);
  53128. this._sinPitch = Math.sin(this._halfpitch);
  53129. this._cosPitch = Math.cos(this._halfpitch);
  53130. this._sinYaw = Math.sin(this._halfyaw);
  53131. this._cosYaw = Math.cos(this._halfyaw);
  53132. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53133. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53134. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53135. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53136. };
  53137. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53138. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53139. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53140. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53141. this._rotMatrix.m[3] = 0;
  53142. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53143. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53144. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53145. this._rotMatrix.m[7] = 0;
  53146. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53147. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53148. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53149. this._rotMatrix.m[11] = 0;
  53150. this._rotMatrix.m[12] = 0;
  53151. this._rotMatrix.m[13] = 0;
  53152. this._rotMatrix.m[14] = 0;
  53153. this._rotMatrix.m[15] = 1.0;
  53154. };
  53155. /**
  53156. * Disposes the SPS.
  53157. */
  53158. SolidParticleSystem.prototype.dispose = function () {
  53159. this.mesh.dispose();
  53160. this.vars = null;
  53161. // drop references to internal big arrays for the GC
  53162. this._positions = null;
  53163. this._indices = null;
  53164. this._normals = null;
  53165. this._uvs = null;
  53166. this._colors = null;
  53167. this._indices32 = null;
  53168. this._positions32 = null;
  53169. this._normals32 = null;
  53170. this._fixedNormal32 = null;
  53171. this._uvs32 = null;
  53172. this._colors32 = null;
  53173. this.pickedParticles = null;
  53174. };
  53175. /**
  53176. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53177. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53178. * @returns the SPS.
  53179. */
  53180. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53181. if (!this._isVisibilityBoxLocked) {
  53182. this.mesh.refreshBoundingInfo();
  53183. }
  53184. return this;
  53185. };
  53186. /**
  53187. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53188. * @param size the size (float) of the visibility box
  53189. * note : this doesn't lock the SPS mesh bounding box.
  53190. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53191. */
  53192. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53193. var vis = size / 2;
  53194. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53195. };
  53196. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53197. /**
  53198. * Gets whether the SPS as always visible or not
  53199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53200. */
  53201. get: function () {
  53202. return this._alwaysVisible;
  53203. },
  53204. /**
  53205. * Sets the SPS as always visible or not
  53206. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53207. */
  53208. set: function (val) {
  53209. this._alwaysVisible = val;
  53210. this.mesh.alwaysSelectAsActiveMesh = val;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53216. /**
  53217. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53218. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53219. */
  53220. get: function () {
  53221. return this._isVisibilityBoxLocked;
  53222. },
  53223. /**
  53224. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53225. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53226. */
  53227. set: function (val) {
  53228. this._isVisibilityBoxLocked = val;
  53229. var boundingInfo = this.mesh.getBoundingInfo();
  53230. boundingInfo.isLocked = val;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53236. /**
  53237. * Gets if `setParticles()` computes the particle rotations or not.
  53238. * Default value : true. The SPS is faster when it's set to false.
  53239. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53240. */
  53241. get: function () {
  53242. return this._computeParticleRotation;
  53243. },
  53244. /**
  53245. * Tells to `setParticles()` to compute the particle rotations or not.
  53246. * Default value : true. The SPS is faster when it's set to false.
  53247. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53248. */
  53249. set: function (val) {
  53250. this._computeParticleRotation = val;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53256. /**
  53257. * Gets if `setParticles()` computes the particle colors or not.
  53258. * Default value : true. The SPS is faster when it's set to false.
  53259. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53260. */
  53261. get: function () {
  53262. return this._computeParticleColor;
  53263. },
  53264. /**
  53265. * Tells to `setParticles()` to compute the particle colors or not.
  53266. * Default value : true. The SPS is faster when it's set to false.
  53267. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53268. */
  53269. set: function (val) {
  53270. this._computeParticleColor = val;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53276. /**
  53277. * Gets if `setParticles()` computes the particle textures or not.
  53278. * Default value : true. The SPS is faster when it's set to false.
  53279. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53280. */
  53281. get: function () {
  53282. return this._computeParticleTexture;
  53283. },
  53284. set: function (val) {
  53285. this._computeParticleTexture = val;
  53286. },
  53287. enumerable: true,
  53288. configurable: true
  53289. });
  53290. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53291. /**
  53292. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53293. * Default value : false. The SPS is faster when it's set to false.
  53294. * Note : the particle custom vertex positions aren't stored values.
  53295. */
  53296. get: function () {
  53297. return this._computeParticleVertex;
  53298. },
  53299. /**
  53300. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53301. * Default value : false. The SPS is faster when it's set to false.
  53302. * Note : the particle custom vertex positions aren't stored values.
  53303. */
  53304. set: function (val) {
  53305. this._computeParticleVertex = val;
  53306. },
  53307. enumerable: true,
  53308. configurable: true
  53309. });
  53310. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53311. /**
  53312. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53313. */
  53314. get: function () {
  53315. return this._computeBoundingBox;
  53316. },
  53317. /**
  53318. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53319. */
  53320. set: function (val) {
  53321. this._computeBoundingBox = val;
  53322. },
  53323. enumerable: true,
  53324. configurable: true
  53325. });
  53326. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53327. /**
  53328. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53329. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53330. * Default : `true`
  53331. */
  53332. get: function () {
  53333. return this._depthSortParticles;
  53334. },
  53335. /**
  53336. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53337. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53338. * Default : `true`
  53339. */
  53340. set: function (val) {
  53341. this._depthSortParticles = val;
  53342. },
  53343. enumerable: true,
  53344. configurable: true
  53345. });
  53346. // =======================================================================
  53347. // Particle behavior logic
  53348. // these following methods may be overwritten by the user to fit his needs
  53349. /**
  53350. * This function does nothing. It may be overwritten to set all the particle first values.
  53351. * The SPS doesn't call this function, you may have to call it by your own.
  53352. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53353. */
  53354. SolidParticleSystem.prototype.initParticles = function () {
  53355. };
  53356. /**
  53357. * This function does nothing. It may be overwritten to recycle a particle.
  53358. * The SPS doesn't call this function, you may have to call it by your own.
  53359. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53360. * @param particle The particle to recycle
  53361. * @returns the recycled particle
  53362. */
  53363. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53364. return particle;
  53365. };
  53366. /**
  53367. * Updates a particle : this function should be overwritten by the user.
  53368. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53369. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53370. * @example : just set a particle position or velocity and recycle conditions
  53371. * @param particle The particle to update
  53372. * @returns the updated particle
  53373. */
  53374. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53375. return particle;
  53376. };
  53377. /**
  53378. * Updates a vertex of a particle : it can be overwritten by the user.
  53379. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53380. * @param particle the current particle
  53381. * @param vertex the current index of the current particle
  53382. * @param pt the index of the current vertex in the particle shape
  53383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53384. * @example : just set a vertex particle position
  53385. * @returns the updated vertex
  53386. */
  53387. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53388. return vertex;
  53389. };
  53390. /**
  53391. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53392. * This does nothing and may be overwritten by the user.
  53393. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53394. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53395. * @param update the boolean update value actually passed to setParticles()
  53396. */
  53397. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53398. };
  53399. /**
  53400. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53401. * This will be passed three parameters.
  53402. * This does nothing and may be overwritten by the user.
  53403. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53404. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53405. * @param update the boolean update value actually passed to setParticles()
  53406. */
  53407. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53408. };
  53409. return SolidParticleSystem;
  53410. }());
  53411. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53412. })(BABYLON || (BABYLON = {}));
  53413. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53414. var BABYLON;
  53415. (function (BABYLON) {
  53416. var ShaderMaterial = /** @class */ (function (_super) {
  53417. __extends(ShaderMaterial, _super);
  53418. function ShaderMaterial(name, scene, shaderPath, options) {
  53419. var _this = _super.call(this, name, scene) || this;
  53420. _this._textures = {};
  53421. _this._textureArrays = {};
  53422. _this._floats = {};
  53423. _this._ints = {};
  53424. _this._floatsArrays = {};
  53425. _this._colors3 = {};
  53426. _this._colors3Arrays = {};
  53427. _this._colors4 = {};
  53428. _this._vectors2 = {};
  53429. _this._vectors3 = {};
  53430. _this._vectors4 = {};
  53431. _this._matrices = {};
  53432. _this._matrices3x3 = {};
  53433. _this._matrices2x2 = {};
  53434. _this._vectors2Arrays = {};
  53435. _this._vectors3Arrays = {};
  53436. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53437. _this._shaderPath = shaderPath;
  53438. options.needAlphaBlending = options.needAlphaBlending || false;
  53439. options.needAlphaTesting = options.needAlphaTesting || false;
  53440. options.attributes = options.attributes || ["position", "normal", "uv"];
  53441. options.uniforms = options.uniforms || ["worldViewProjection"];
  53442. options.uniformBuffers = options.uniformBuffers || [];
  53443. options.samplers = options.samplers || [];
  53444. options.defines = options.defines || [];
  53445. _this._options = options;
  53446. return _this;
  53447. }
  53448. ShaderMaterial.prototype.getClassName = function () {
  53449. return "ShaderMaterial";
  53450. };
  53451. ShaderMaterial.prototype.needAlphaBlending = function () {
  53452. return this._options.needAlphaBlending;
  53453. };
  53454. ShaderMaterial.prototype.needAlphaTesting = function () {
  53455. return this._options.needAlphaTesting;
  53456. };
  53457. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53458. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53459. this._options.uniforms.push(uniformName);
  53460. }
  53461. };
  53462. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53463. if (this._options.samplers.indexOf(name) === -1) {
  53464. this._options.samplers.push(name);
  53465. }
  53466. this._textures[name] = texture;
  53467. return this;
  53468. };
  53469. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53470. if (this._options.samplers.indexOf(name) === -1) {
  53471. this._options.samplers.push(name);
  53472. }
  53473. this._checkUniform(name);
  53474. this._textureArrays[name] = textures;
  53475. return this;
  53476. };
  53477. ShaderMaterial.prototype.setFloat = function (name, value) {
  53478. this._checkUniform(name);
  53479. this._floats[name] = value;
  53480. return this;
  53481. };
  53482. ShaderMaterial.prototype.setInt = function (name, value) {
  53483. this._checkUniform(name);
  53484. this._ints[name] = value;
  53485. return this;
  53486. };
  53487. ShaderMaterial.prototype.setFloats = function (name, value) {
  53488. this._checkUniform(name);
  53489. this._floatsArrays[name] = value;
  53490. return this;
  53491. };
  53492. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53493. this._checkUniform(name);
  53494. this._colors3[name] = value;
  53495. return this;
  53496. };
  53497. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53498. this._checkUniform(name);
  53499. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53500. color.toArray(arr, arr.length);
  53501. return arr;
  53502. }, []);
  53503. return this;
  53504. };
  53505. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53506. this._checkUniform(name);
  53507. this._colors4[name] = value;
  53508. return this;
  53509. };
  53510. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53511. this._checkUniform(name);
  53512. this._vectors2[name] = value;
  53513. return this;
  53514. };
  53515. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53516. this._checkUniform(name);
  53517. this._vectors3[name] = value;
  53518. return this;
  53519. };
  53520. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53521. this._checkUniform(name);
  53522. this._vectors4[name] = value;
  53523. return this;
  53524. };
  53525. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53526. this._checkUniform(name);
  53527. this._matrices[name] = value;
  53528. return this;
  53529. };
  53530. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53531. this._checkUniform(name);
  53532. this._matrices3x3[name] = value;
  53533. return this;
  53534. };
  53535. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53536. this._checkUniform(name);
  53537. this._matrices2x2[name] = value;
  53538. return this;
  53539. };
  53540. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53541. this._checkUniform(name);
  53542. this._vectors2Arrays[name] = value;
  53543. return this;
  53544. };
  53545. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53546. this._checkUniform(name);
  53547. this._vectors3Arrays[name] = value;
  53548. return this;
  53549. };
  53550. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53551. if (!mesh) {
  53552. return true;
  53553. }
  53554. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53555. return false;
  53556. }
  53557. return false;
  53558. };
  53559. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53560. var scene = this.getScene();
  53561. var engine = scene.getEngine();
  53562. if (!this.checkReadyOnEveryCall) {
  53563. if (this._renderId === scene.getRenderId()) {
  53564. if (this._checkCache(scene, mesh, useInstances)) {
  53565. return true;
  53566. }
  53567. }
  53568. }
  53569. // Instances
  53570. var defines = [];
  53571. var attribs = [];
  53572. var fallbacks = new BABYLON.EffectFallbacks();
  53573. if (useInstances) {
  53574. defines.push("#define INSTANCES");
  53575. }
  53576. for (var index = 0; index < this._options.defines.length; index++) {
  53577. defines.push(this._options.defines[index]);
  53578. }
  53579. for (var index = 0; index < this._options.attributes.length; index++) {
  53580. attribs.push(this._options.attributes[index]);
  53581. }
  53582. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53583. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53584. defines.push("#define VERTEXCOLOR");
  53585. }
  53586. // Bones
  53587. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53588. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53589. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53590. if (mesh.numBoneInfluencers > 4) {
  53591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53593. }
  53594. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53595. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53596. fallbacks.addCPUSkinningFallback(0, mesh);
  53597. if (this._options.uniforms.indexOf("mBones") === -1) {
  53598. this._options.uniforms.push("mBones");
  53599. }
  53600. }
  53601. else {
  53602. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53603. }
  53604. // Textures
  53605. for (var name in this._textures) {
  53606. if (!this._textures[name].isReady()) {
  53607. return false;
  53608. }
  53609. }
  53610. // Alpha test
  53611. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53612. defines.push("#define ALPHATEST");
  53613. }
  53614. var previousEffect = this._effect;
  53615. var join = defines.join("\n");
  53616. this._effect = engine.createEffect(this._shaderPath, {
  53617. attributes: attribs,
  53618. uniformsNames: this._options.uniforms,
  53619. uniformBuffersNames: this._options.uniformBuffers,
  53620. samplers: this._options.samplers,
  53621. defines: join,
  53622. fallbacks: fallbacks,
  53623. onCompiled: this.onCompiled,
  53624. onError: this.onError
  53625. }, engine);
  53626. if (!this._effect.isReady()) {
  53627. return false;
  53628. }
  53629. if (previousEffect !== this._effect) {
  53630. scene.resetCachedMaterial();
  53631. }
  53632. this._renderId = scene.getRenderId();
  53633. return true;
  53634. };
  53635. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53636. var scene = this.getScene();
  53637. if (!this._effect) {
  53638. return;
  53639. }
  53640. if (this._options.uniforms.indexOf("world") !== -1) {
  53641. this._effect.setMatrix("world", world);
  53642. }
  53643. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53644. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53645. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53646. }
  53647. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53648. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53649. }
  53650. };
  53651. ShaderMaterial.prototype.bind = function (world, mesh) {
  53652. // Std values
  53653. this.bindOnlyWorldMatrix(world);
  53654. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53655. if (this._options.uniforms.indexOf("view") !== -1) {
  53656. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53657. }
  53658. if (this._options.uniforms.indexOf("projection") !== -1) {
  53659. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53660. }
  53661. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53662. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53663. }
  53664. // Bones
  53665. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53666. var name;
  53667. // Texture
  53668. for (name in this._textures) {
  53669. this._effect.setTexture(name, this._textures[name]);
  53670. }
  53671. // Texture arrays
  53672. for (name in this._textureArrays) {
  53673. this._effect.setTextureArray(name, this._textureArrays[name]);
  53674. }
  53675. // Int
  53676. for (name in this._ints) {
  53677. this._effect.setInt(name, this._ints[name]);
  53678. }
  53679. // Float
  53680. for (name in this._floats) {
  53681. this._effect.setFloat(name, this._floats[name]);
  53682. }
  53683. // Floats
  53684. for (name in this._floatsArrays) {
  53685. this._effect.setArray(name, this._floatsArrays[name]);
  53686. }
  53687. // Color3
  53688. for (name in this._colors3) {
  53689. this._effect.setColor3(name, this._colors3[name]);
  53690. }
  53691. for (name in this._colors3Arrays) {
  53692. this._effect.setArray3(name, this._colors3Arrays[name]);
  53693. }
  53694. // Color4
  53695. for (name in this._colors4) {
  53696. var color = this._colors4[name];
  53697. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53698. }
  53699. // Vector2
  53700. for (name in this._vectors2) {
  53701. this._effect.setVector2(name, this._vectors2[name]);
  53702. }
  53703. // Vector3
  53704. for (name in this._vectors3) {
  53705. this._effect.setVector3(name, this._vectors3[name]);
  53706. }
  53707. // Vector4
  53708. for (name in this._vectors4) {
  53709. this._effect.setVector4(name, this._vectors4[name]);
  53710. }
  53711. // Matrix
  53712. for (name in this._matrices) {
  53713. this._effect.setMatrix(name, this._matrices[name]);
  53714. }
  53715. // Matrix 3x3
  53716. for (name in this._matrices3x3) {
  53717. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53718. }
  53719. // Matrix 2x2
  53720. for (name in this._matrices2x2) {
  53721. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53722. }
  53723. // Vector2Array
  53724. for (name in this._vectors2Arrays) {
  53725. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53726. }
  53727. // Vector3Array
  53728. for (name in this._vectors3Arrays) {
  53729. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53730. }
  53731. }
  53732. this._afterBind(mesh);
  53733. };
  53734. ShaderMaterial.prototype.getActiveTextures = function () {
  53735. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53736. for (var name in this._textures) {
  53737. activeTextures.push(this._textures[name]);
  53738. }
  53739. for (var name in this._textureArrays) {
  53740. var array = this._textureArrays[name];
  53741. for (var index = 0; index < array.length; index++) {
  53742. activeTextures.push(array[index]);
  53743. }
  53744. }
  53745. return activeTextures;
  53746. };
  53747. ShaderMaterial.prototype.hasTexture = function (texture) {
  53748. if (_super.prototype.hasTexture.call(this, texture)) {
  53749. return true;
  53750. }
  53751. for (var name in this._textures) {
  53752. if (this._textures[name] === texture) {
  53753. return true;
  53754. }
  53755. }
  53756. for (var name in this._textureArrays) {
  53757. var array = this._textureArrays[name];
  53758. for (var index = 0; index < array.length; index++) {
  53759. if (array[index] === texture) {
  53760. return true;
  53761. }
  53762. }
  53763. }
  53764. return false;
  53765. };
  53766. ShaderMaterial.prototype.clone = function (name) {
  53767. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53768. return newShaderMaterial;
  53769. };
  53770. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53771. if (forceDisposeTextures) {
  53772. var name;
  53773. for (name in this._textures) {
  53774. this._textures[name].dispose();
  53775. }
  53776. for (name in this._textureArrays) {
  53777. var array = this._textureArrays[name];
  53778. for (var index = 0; index < array.length; index++) {
  53779. array[index].dispose();
  53780. }
  53781. }
  53782. }
  53783. this._textures = {};
  53784. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53785. };
  53786. ShaderMaterial.prototype.serialize = function () {
  53787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53788. serializationObject.customType = "BABYLON.ShaderMaterial";
  53789. serializationObject.options = this._options;
  53790. serializationObject.shaderPath = this._shaderPath;
  53791. var name;
  53792. // Texture
  53793. serializationObject.textures = {};
  53794. for (name in this._textures) {
  53795. serializationObject.textures[name] = this._textures[name].serialize();
  53796. }
  53797. // Texture arrays
  53798. serializationObject.textureArrays = {};
  53799. for (name in this._textureArrays) {
  53800. serializationObject.textureArrays[name] = [];
  53801. var array = this._textureArrays[name];
  53802. for (var index = 0; index < array.length; index++) {
  53803. serializationObject.textureArrays[name].push(array[index].serialize());
  53804. }
  53805. }
  53806. // Float
  53807. serializationObject.floats = {};
  53808. for (name in this._floats) {
  53809. serializationObject.floats[name] = this._floats[name];
  53810. }
  53811. // Float s
  53812. serializationObject.FloatArrays = {};
  53813. for (name in this._floatsArrays) {
  53814. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53815. }
  53816. // Color3
  53817. serializationObject.colors3 = {};
  53818. for (name in this._colors3) {
  53819. serializationObject.colors3[name] = this._colors3[name].asArray();
  53820. }
  53821. // Color3 array
  53822. serializationObject.colors3Arrays = {};
  53823. for (name in this._colors3Arrays) {
  53824. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53825. }
  53826. // Color4
  53827. serializationObject.colors4 = {};
  53828. for (name in this._colors4) {
  53829. serializationObject.colors4[name] = this._colors4[name].asArray();
  53830. }
  53831. // Vector2
  53832. serializationObject.vectors2 = {};
  53833. for (name in this._vectors2) {
  53834. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53835. }
  53836. // Vector3
  53837. serializationObject.vectors3 = {};
  53838. for (name in this._vectors3) {
  53839. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53840. }
  53841. // Vector4
  53842. serializationObject.vectors4 = {};
  53843. for (name in this._vectors4) {
  53844. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53845. }
  53846. // Matrix
  53847. serializationObject.matrices = {};
  53848. for (name in this._matrices) {
  53849. serializationObject.matrices[name] = this._matrices[name].asArray();
  53850. }
  53851. // Matrix 3x3
  53852. serializationObject.matrices3x3 = {};
  53853. for (name in this._matrices3x3) {
  53854. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53855. }
  53856. // Matrix 2x2
  53857. serializationObject.matrices2x2 = {};
  53858. for (name in this._matrices2x2) {
  53859. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53860. }
  53861. // Vector2Array
  53862. serializationObject.vectors2Arrays = {};
  53863. for (name in this._vectors2Arrays) {
  53864. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53865. }
  53866. // Vector3Array
  53867. serializationObject.vectors3Arrays = {};
  53868. for (name in this._vectors3Arrays) {
  53869. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53870. }
  53871. return serializationObject;
  53872. };
  53873. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53874. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53875. var name;
  53876. // Texture
  53877. for (name in source.textures) {
  53878. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53879. }
  53880. // Texture arrays
  53881. for (name in source.textureArrays) {
  53882. var array = source.textureArrays[name];
  53883. var textureArray = new Array();
  53884. for (var index = 0; index < array.length; index++) {
  53885. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53886. }
  53887. material.setTextureArray(name, textureArray);
  53888. }
  53889. // Float
  53890. for (name in source.floats) {
  53891. material.setFloat(name, source.floats[name]);
  53892. }
  53893. // Float s
  53894. for (name in source.floatsArrays) {
  53895. material.setFloats(name, source.floatsArrays[name]);
  53896. }
  53897. // Color3
  53898. for (name in source.colors3) {
  53899. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53900. }
  53901. // Color3 arrays
  53902. for (name in source.colors3Arrays) {
  53903. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53904. if (i % 3 === 0) {
  53905. arr.push([num]);
  53906. }
  53907. else {
  53908. arr[arr.length - 1].push(num);
  53909. }
  53910. return arr;
  53911. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53912. material.setColor3Array(name, colors);
  53913. }
  53914. // Color4
  53915. for (name in source.colors4) {
  53916. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53917. }
  53918. // Vector2
  53919. for (name in source.vectors2) {
  53920. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53921. }
  53922. // Vector3
  53923. for (name in source.vectors3) {
  53924. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53925. }
  53926. // Vector4
  53927. for (name in source.vectors4) {
  53928. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53929. }
  53930. // Matrix
  53931. for (name in source.matrices) {
  53932. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53933. }
  53934. // Matrix 3x3
  53935. for (name in source.matrices3x3) {
  53936. material.setMatrix3x3(name, source.matrices3x3[name]);
  53937. }
  53938. // Matrix 2x2
  53939. for (name in source.matrices2x2) {
  53940. material.setMatrix2x2(name, source.matrices2x2[name]);
  53941. }
  53942. // Vector2Array
  53943. for (name in source.vectors2Arrays) {
  53944. material.setArray2(name, source.vectors2Arrays[name]);
  53945. }
  53946. // Vector3Array
  53947. for (name in source.vectors3Arrays) {
  53948. material.setArray3(name, source.vectors3Arrays[name]);
  53949. }
  53950. return material;
  53951. };
  53952. return ShaderMaterial;
  53953. }(BABYLON.Material));
  53954. BABYLON.ShaderMaterial = ShaderMaterial;
  53955. })(BABYLON || (BABYLON = {}));
  53956. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53957. var BABYLON;
  53958. (function (BABYLON) {
  53959. var GroundMesh = /** @class */ (function (_super) {
  53960. __extends(GroundMesh, _super);
  53961. function GroundMesh(name, scene) {
  53962. var _this = _super.call(this, name, scene) || this;
  53963. _this.generateOctree = false;
  53964. return _this;
  53965. }
  53966. GroundMesh.prototype.getClassName = function () {
  53967. return "GroundMesh";
  53968. };
  53969. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53970. get: function () {
  53971. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53972. },
  53973. enumerable: true,
  53974. configurable: true
  53975. });
  53976. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53977. get: function () {
  53978. return this._subdivisionsX;
  53979. },
  53980. enumerable: true,
  53981. configurable: true
  53982. });
  53983. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53984. get: function () {
  53985. return this._subdivisionsY;
  53986. },
  53987. enumerable: true,
  53988. configurable: true
  53989. });
  53990. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53991. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53992. this._subdivisionsX = chunksCount;
  53993. this._subdivisionsY = chunksCount;
  53994. this.subdivide(chunksCount);
  53995. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53996. };
  53997. /**
  53998. * Returns a height (y) value in the Worl system :
  53999. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54000. * Returns the ground y position if (x, z) are outside the ground surface.
  54001. */
  54002. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54003. var world = this.getWorldMatrix();
  54004. var invMat = BABYLON.Tmp.Matrix[5];
  54005. world.invertToRef(invMat);
  54006. var tmpVect = BABYLON.Tmp.Vector3[8];
  54007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54008. x = tmpVect.x;
  54009. z = tmpVect.z;
  54010. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54011. return this.position.y;
  54012. }
  54013. if (!this._heightQuads || this._heightQuads.length == 0) {
  54014. this._initHeightQuads();
  54015. this._computeHeightQuads();
  54016. }
  54017. var facet = this._getFacetAt(x, z);
  54018. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54019. // return y in the World system
  54020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54021. return tmpVect.y;
  54022. };
  54023. /**
  54024. * Returns a normalized vector (Vector3) orthogonal to the ground
  54025. * at the ground coordinates (x, z) expressed in the World system.
  54026. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54027. */
  54028. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54029. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54030. this.getNormalAtCoordinatesToRef(x, z, normal);
  54031. return normal;
  54032. };
  54033. /**
  54034. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54035. * at the ground coordinates (x, z) expressed in the World system.
  54036. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54037. * Returns the GroundMesh.
  54038. */
  54039. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54040. var world = this.getWorldMatrix();
  54041. var tmpMat = BABYLON.Tmp.Matrix[5];
  54042. world.invertToRef(tmpMat);
  54043. var tmpVect = BABYLON.Tmp.Vector3[8];
  54044. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54045. x = tmpVect.x;
  54046. z = tmpVect.z;
  54047. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54048. return this;
  54049. }
  54050. if (!this._heightQuads || this._heightQuads.length == 0) {
  54051. this._initHeightQuads();
  54052. this._computeHeightQuads();
  54053. }
  54054. var facet = this._getFacetAt(x, z);
  54055. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54056. return this;
  54057. };
  54058. /**
  54059. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54060. * if the ground has been updated.
  54061. * This can be used in the render loop.
  54062. * Returns the GroundMesh.
  54063. */
  54064. GroundMesh.prototype.updateCoordinateHeights = function () {
  54065. if (!this._heightQuads || this._heightQuads.length == 0) {
  54066. this._initHeightQuads();
  54067. }
  54068. this._computeHeightQuads();
  54069. return this;
  54070. };
  54071. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54072. GroundMesh.prototype._getFacetAt = function (x, z) {
  54073. // retrieve col and row from x, z coordinates in the ground local system
  54074. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54075. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54076. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54077. var facet;
  54078. if (z < quad.slope.x * x + quad.slope.y) {
  54079. facet = quad.facet1;
  54080. }
  54081. else {
  54082. facet = quad.facet2;
  54083. }
  54084. return facet;
  54085. };
  54086. // Creates and populates the heightMap array with "facet" elements :
  54087. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54088. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54089. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54090. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54091. // Returns the GroundMesh.
  54092. GroundMesh.prototype._initHeightQuads = function () {
  54093. var subdivisionsX = this._subdivisionsX;
  54094. var subdivisionsY = this._subdivisionsY;
  54095. this._heightQuads = new Array();
  54096. for (var row = 0; row < subdivisionsY; row++) {
  54097. for (var col = 0; col < subdivisionsX; col++) {
  54098. 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) };
  54099. this._heightQuads[row * subdivisionsX + col] = quad;
  54100. }
  54101. }
  54102. return this;
  54103. };
  54104. // Compute each quad element values and update the the heightMap array :
  54105. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54106. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54107. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54108. // Returns the GroundMesh.
  54109. GroundMesh.prototype._computeHeightQuads = function () {
  54110. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54111. if (!positions) {
  54112. return this;
  54113. }
  54114. var v1 = BABYLON.Tmp.Vector3[3];
  54115. var v2 = BABYLON.Tmp.Vector3[2];
  54116. var v3 = BABYLON.Tmp.Vector3[1];
  54117. var v4 = BABYLON.Tmp.Vector3[0];
  54118. var v1v2 = BABYLON.Tmp.Vector3[4];
  54119. var v1v3 = BABYLON.Tmp.Vector3[5];
  54120. var v1v4 = BABYLON.Tmp.Vector3[6];
  54121. var norm1 = BABYLON.Tmp.Vector3[7];
  54122. var norm2 = BABYLON.Tmp.Vector3[8];
  54123. var i = 0;
  54124. var j = 0;
  54125. var k = 0;
  54126. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54127. var h = 0;
  54128. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54129. var d2 = 0;
  54130. var subdivisionsX = this._subdivisionsX;
  54131. var subdivisionsY = this._subdivisionsY;
  54132. for (var row = 0; row < subdivisionsY; row++) {
  54133. for (var col = 0; col < subdivisionsX; col++) {
  54134. i = col * 3;
  54135. j = row * (subdivisionsX + 1) * 3;
  54136. k = (row + 1) * (subdivisionsX + 1) * 3;
  54137. v1.x = positions[j + i];
  54138. v1.y = positions[j + i + 1];
  54139. v1.z = positions[j + i + 2];
  54140. v2.x = positions[j + i + 3];
  54141. v2.y = positions[j + i + 4];
  54142. v2.z = positions[j + i + 5];
  54143. v3.x = positions[k + i];
  54144. v3.y = positions[k + i + 1];
  54145. v3.z = positions[k + i + 2];
  54146. v4.x = positions[k + i + 3];
  54147. v4.y = positions[k + i + 4];
  54148. v4.z = positions[k + i + 5];
  54149. // 2D slope V1V4
  54150. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54151. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54152. // facet equations :
  54153. // we compute each facet normal vector
  54154. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54155. // we compute the value d by applying the equation to v1 which belongs to the plane
  54156. // then we store the facet equation in a Vector4
  54157. v2.subtractToRef(v1, v1v2);
  54158. v3.subtractToRef(v1, v1v3);
  54159. v4.subtractToRef(v1, v1v4);
  54160. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54161. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54162. norm1.normalize();
  54163. norm2.normalize();
  54164. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54165. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54166. var quad = this._heightQuads[row * subdivisionsX + col];
  54167. quad.slope.copyFromFloats(cd, h);
  54168. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54169. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54170. }
  54171. }
  54172. return this;
  54173. };
  54174. GroundMesh.prototype.serialize = function (serializationObject) {
  54175. _super.prototype.serialize.call(this, serializationObject);
  54176. serializationObject.subdivisionsX = this._subdivisionsX;
  54177. serializationObject.subdivisionsY = this._subdivisionsY;
  54178. serializationObject.minX = this._minX;
  54179. serializationObject.maxX = this._maxX;
  54180. serializationObject.minZ = this._minZ;
  54181. serializationObject.maxZ = this._maxZ;
  54182. serializationObject.width = this._width;
  54183. serializationObject.height = this._height;
  54184. };
  54185. GroundMesh.Parse = function (parsedMesh, scene) {
  54186. var result = new GroundMesh(parsedMesh.name, scene);
  54187. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54188. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54189. result._minX = parsedMesh.minX;
  54190. result._maxX = parsedMesh.maxX;
  54191. result._minZ = parsedMesh.minZ;
  54192. result._maxZ = parsedMesh.maxZ;
  54193. result._width = parsedMesh.width;
  54194. result._height = parsedMesh.height;
  54195. return result;
  54196. };
  54197. return GroundMesh;
  54198. }(BABYLON.Mesh));
  54199. BABYLON.GroundMesh = GroundMesh;
  54200. })(BABYLON || (BABYLON = {}));
  54201. //# sourceMappingURL=babylon.groundMesh.js.map
  54202. var BABYLON;
  54203. (function (BABYLON) {
  54204. /**
  54205. * Creates an instance based on a source mesh.
  54206. */
  54207. var InstancedMesh = /** @class */ (function (_super) {
  54208. __extends(InstancedMesh, _super);
  54209. function InstancedMesh(name, source) {
  54210. var _this = _super.call(this, name, source.getScene()) || this;
  54211. source.instances.push(_this);
  54212. _this._sourceMesh = source;
  54213. _this.position.copyFrom(source.position);
  54214. _this.rotation.copyFrom(source.rotation);
  54215. _this.scaling.copyFrom(source.scaling);
  54216. if (source.rotationQuaternion) {
  54217. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54218. }
  54219. _this.infiniteDistance = source.infiniteDistance;
  54220. _this.setPivotMatrix(source.getPivotMatrix());
  54221. _this.refreshBoundingInfo();
  54222. _this._syncSubMeshes();
  54223. return _this;
  54224. }
  54225. /**
  54226. * Returns the string "InstancedMesh".
  54227. */
  54228. InstancedMesh.prototype.getClassName = function () {
  54229. return "InstancedMesh";
  54230. };
  54231. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54232. // Methods
  54233. get: function () {
  54234. return this._sourceMesh.receiveShadows;
  54235. },
  54236. enumerable: true,
  54237. configurable: true
  54238. });
  54239. Object.defineProperty(InstancedMesh.prototype, "material", {
  54240. get: function () {
  54241. return this._sourceMesh.material;
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54247. get: function () {
  54248. return this._sourceMesh.visibility;
  54249. },
  54250. enumerable: true,
  54251. configurable: true
  54252. });
  54253. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54254. get: function () {
  54255. return this._sourceMesh.skeleton;
  54256. },
  54257. enumerable: true,
  54258. configurable: true
  54259. });
  54260. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54261. get: function () {
  54262. return this._sourceMesh.renderingGroupId;
  54263. },
  54264. enumerable: true,
  54265. configurable: true
  54266. });
  54267. /**
  54268. * Returns the total number of vertices (integer).
  54269. */
  54270. InstancedMesh.prototype.getTotalVertices = function () {
  54271. return this._sourceMesh.getTotalVertices();
  54272. };
  54273. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54274. get: function () {
  54275. return this._sourceMesh;
  54276. },
  54277. enumerable: true,
  54278. configurable: true
  54279. });
  54280. /**
  54281. * Is this node ready to be used/rendered
  54282. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54283. * @return {boolean} is it ready
  54284. */
  54285. InstancedMesh.prototype.isReady = function (completeCheck) {
  54286. if (completeCheck === void 0) { completeCheck = false; }
  54287. return this._sourceMesh.isReady(completeCheck, true);
  54288. };
  54289. /**
  54290. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54291. */
  54292. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54293. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54294. };
  54295. /**
  54296. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54297. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54298. * The `data` are either a numeric array either a Float32Array.
  54299. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54300. * 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).
  54301. * Note that a new underlying VertexBuffer object is created each call.
  54302. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54303. *
  54304. * Possible `kind` values :
  54305. * - BABYLON.VertexBuffer.PositionKind
  54306. * - BABYLON.VertexBuffer.UVKind
  54307. * - BABYLON.VertexBuffer.UV2Kind
  54308. * - BABYLON.VertexBuffer.UV3Kind
  54309. * - BABYLON.VertexBuffer.UV4Kind
  54310. * - BABYLON.VertexBuffer.UV5Kind
  54311. * - BABYLON.VertexBuffer.UV6Kind
  54312. * - BABYLON.VertexBuffer.ColorKind
  54313. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54314. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54315. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54316. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54317. *
  54318. * Returns the Mesh.
  54319. */
  54320. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54321. if (this.sourceMesh) {
  54322. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54323. }
  54324. return this.sourceMesh;
  54325. };
  54326. /**
  54327. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54328. * If the mesh has no geometry, it is simply returned as it is.
  54329. * The `data` are either a numeric array either a Float32Array.
  54330. * No new underlying VertexBuffer object is created.
  54331. * 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.
  54332. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54333. *
  54334. * Possible `kind` values :
  54335. * - BABYLON.VertexBuffer.PositionKind
  54336. * - BABYLON.VertexBuffer.UVKind
  54337. * - BABYLON.VertexBuffer.UV2Kind
  54338. * - BABYLON.VertexBuffer.UV3Kind
  54339. * - BABYLON.VertexBuffer.UV4Kind
  54340. * - BABYLON.VertexBuffer.UV5Kind
  54341. * - BABYLON.VertexBuffer.UV6Kind
  54342. * - BABYLON.VertexBuffer.ColorKind
  54343. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54344. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54345. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54346. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54347. *
  54348. * Returns the Mesh.
  54349. */
  54350. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54351. if (this.sourceMesh) {
  54352. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54353. }
  54354. return this.sourceMesh;
  54355. };
  54356. /**
  54357. * Sets the mesh indices.
  54358. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54359. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54360. * This method creates a new index buffer each call.
  54361. * Returns the Mesh.
  54362. */
  54363. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54364. if (totalVertices === void 0) { totalVertices = null; }
  54365. if (this.sourceMesh) {
  54366. this.sourceMesh.setIndices(indices, totalVertices);
  54367. }
  54368. return this.sourceMesh;
  54369. };
  54370. /**
  54371. * Boolean : True if the mesh owns the requested kind of data.
  54372. */
  54373. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54374. return this._sourceMesh.isVerticesDataPresent(kind);
  54375. };
  54376. /**
  54377. * Returns an array of indices (IndicesArray).
  54378. */
  54379. InstancedMesh.prototype.getIndices = function () {
  54380. return this._sourceMesh.getIndices();
  54381. };
  54382. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54383. get: function () {
  54384. return this._sourceMesh._positions;
  54385. },
  54386. enumerable: true,
  54387. configurable: true
  54388. });
  54389. /**
  54390. * Sets a new updated BoundingInfo to the mesh.
  54391. * Returns the mesh.
  54392. */
  54393. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54394. var meshBB = this._sourceMesh.getBoundingInfo();
  54395. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54396. this._updateBoundingInfo();
  54397. return this;
  54398. };
  54399. InstancedMesh.prototype._preActivate = function () {
  54400. if (this._currentLOD) {
  54401. this._currentLOD._preActivate();
  54402. }
  54403. return this;
  54404. };
  54405. InstancedMesh.prototype._activate = function (renderId) {
  54406. if (this._currentLOD) {
  54407. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54408. }
  54409. return this;
  54410. };
  54411. /**
  54412. * Returns the current associated LOD AbstractMesh.
  54413. */
  54414. InstancedMesh.prototype.getLOD = function (camera) {
  54415. if (!camera) {
  54416. return this;
  54417. }
  54418. var boundingInfo = this.getBoundingInfo();
  54419. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54420. if (this._currentLOD === this.sourceMesh) {
  54421. return this;
  54422. }
  54423. return this._currentLOD;
  54424. };
  54425. InstancedMesh.prototype._syncSubMeshes = function () {
  54426. this.releaseSubMeshes();
  54427. if (this._sourceMesh.subMeshes) {
  54428. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54429. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54430. }
  54431. }
  54432. return this;
  54433. };
  54434. InstancedMesh.prototype._generatePointsArray = function () {
  54435. return this._sourceMesh._generatePointsArray();
  54436. };
  54437. /**
  54438. * Creates a new InstancedMesh from the current mesh.
  54439. * - name (string) : the cloned mesh name
  54440. * - newParent (optional Node) : the optional Node to parent the clone to.
  54441. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54442. *
  54443. * Returns the clone.
  54444. */
  54445. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54446. var result = this._sourceMesh.createInstance(name);
  54447. // Deep copy
  54448. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54449. // Bounding info
  54450. this.refreshBoundingInfo();
  54451. // Parent
  54452. if (newParent) {
  54453. result.parent = newParent;
  54454. }
  54455. if (!doNotCloneChildren) {
  54456. // Children
  54457. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54458. var mesh = this.getScene().meshes[index];
  54459. if (mesh.parent === this) {
  54460. mesh.clone(mesh.name, result);
  54461. }
  54462. }
  54463. }
  54464. result.computeWorldMatrix(true);
  54465. return result;
  54466. };
  54467. /**
  54468. * Disposes the InstancedMesh.
  54469. * Returns nothing.
  54470. */
  54471. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54472. // Remove from mesh
  54473. var index = this._sourceMesh.instances.indexOf(this);
  54474. this._sourceMesh.instances.splice(index, 1);
  54475. _super.prototype.dispose.call(this, doNotRecurse);
  54476. };
  54477. return InstancedMesh;
  54478. }(BABYLON.AbstractMesh));
  54479. BABYLON.InstancedMesh = InstancedMesh;
  54480. })(BABYLON || (BABYLON = {}));
  54481. //# sourceMappingURL=babylon.instancedMesh.js.map
  54482. var BABYLON;
  54483. (function (BABYLON) {
  54484. var LinesMesh = /** @class */ (function (_super) {
  54485. __extends(LinesMesh, _super);
  54486. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54487. if (scene === void 0) { scene = null; }
  54488. if (parent === void 0) { parent = null; }
  54489. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54490. _this.useVertexColor = useVertexColor;
  54491. _this.useVertexAlpha = useVertexAlpha;
  54492. _this.color = new BABYLON.Color3(1, 1, 1);
  54493. _this.alpha = 1;
  54494. if (source) {
  54495. _this.color = source.color.clone();
  54496. _this.alpha = source.alpha;
  54497. _this.useVertexColor = source.useVertexColor;
  54498. _this.useVertexAlpha = source.useVertexAlpha;
  54499. }
  54500. _this._intersectionThreshold = 0.1;
  54501. var defines = [];
  54502. var options = {
  54503. attributes: [BABYLON.VertexBuffer.PositionKind],
  54504. uniforms: ["world", "viewProjection"],
  54505. needAlphaBlending: true,
  54506. defines: defines
  54507. };
  54508. if (useVertexAlpha === false) {
  54509. options.needAlphaBlending = false;
  54510. }
  54511. if (!useVertexColor) {
  54512. options.uniforms.push("color");
  54513. }
  54514. else {
  54515. options.defines.push("#define VERTEXCOLOR");
  54516. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54517. }
  54518. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54519. return _this;
  54520. }
  54521. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54522. /**
  54523. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54524. * This margin is expressed in world space coordinates, so its value may vary.
  54525. * Default value is 0.1
  54526. * @returns the intersection Threshold value.
  54527. */
  54528. get: function () {
  54529. return this._intersectionThreshold;
  54530. },
  54531. /**
  54532. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54533. * This margin is expressed in world space coordinates, so its value may vary.
  54534. * @param value the new threshold to apply
  54535. */
  54536. set: function (value) {
  54537. if (this._intersectionThreshold === value) {
  54538. return;
  54539. }
  54540. this._intersectionThreshold = value;
  54541. if (this.geometry) {
  54542. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54543. }
  54544. },
  54545. enumerable: true,
  54546. configurable: true
  54547. });
  54548. /**
  54549. * Returns the string "LineMesh"
  54550. */
  54551. LinesMesh.prototype.getClassName = function () {
  54552. return "LinesMesh";
  54553. };
  54554. Object.defineProperty(LinesMesh.prototype, "material", {
  54555. get: function () {
  54556. return this._colorShader;
  54557. },
  54558. set: function (value) {
  54559. // Do nothing
  54560. },
  54561. enumerable: true,
  54562. configurable: true
  54563. });
  54564. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54565. get: function () {
  54566. return false;
  54567. },
  54568. enumerable: true,
  54569. configurable: true
  54570. });
  54571. LinesMesh.prototype.createInstance = function (name) {
  54572. throw new Error("LinesMeshes do not support createInstance.");
  54573. };
  54574. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54575. if (!this._geometry) {
  54576. return this;
  54577. }
  54578. // VBOs
  54579. this._geometry._bind(this._colorShader.getEffect());
  54580. // Color
  54581. if (!this.useVertexColor) {
  54582. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54583. }
  54584. return this;
  54585. };
  54586. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54587. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54588. return this;
  54589. }
  54590. var engine = this.getScene().getEngine();
  54591. // Draw order
  54592. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54593. return this;
  54594. };
  54595. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54596. this._colorShader.dispose();
  54597. _super.prototype.dispose.call(this, doNotRecurse);
  54598. };
  54599. /**
  54600. * Returns a new LineMesh object cloned from the current one.
  54601. */
  54602. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54603. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54604. };
  54605. return LinesMesh;
  54606. }(BABYLON.Mesh));
  54607. BABYLON.LinesMesh = LinesMesh;
  54608. })(BABYLON || (BABYLON = {}));
  54609. //# sourceMappingURL=babylon.linesMesh.js.map
  54610. var BABYLON;
  54611. (function (BABYLON) {
  54612. var MeshBuilder = /** @class */ (function () {
  54613. function MeshBuilder() {
  54614. }
  54615. MeshBuilder.updateSideOrientation = function (orientation) {
  54616. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54617. return BABYLON.Mesh.DOUBLESIDE;
  54618. }
  54619. if (orientation === undefined || orientation === null) {
  54620. return BABYLON.Mesh.FRONTSIDE;
  54621. }
  54622. return orientation;
  54623. };
  54624. /**
  54625. * Creates a box mesh.
  54626. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54627. * The parameter `size` sets the size (float) of each box side (default 1).
  54628. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54629. * 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).
  54630. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54632. * 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).
  54633. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54635. */
  54636. MeshBuilder.CreateBox = function (name, options, scene) {
  54637. if (scene === void 0) { scene = null; }
  54638. var box = new BABYLON.Mesh(name, scene);
  54639. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54640. box._originalBuilderSideOrientation = options.sideOrientation;
  54641. var vertexData = BABYLON.VertexData.CreateBox(options);
  54642. vertexData.applyToMesh(box, options.updatable);
  54643. return box;
  54644. };
  54645. /**
  54646. * Creates a sphere mesh.
  54647. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54648. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54649. * 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`).
  54650. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54651. * 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
  54652. * 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).
  54653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54654. * 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).
  54655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54657. */
  54658. MeshBuilder.CreateSphere = function (name, options, scene) {
  54659. var sphere = new BABYLON.Mesh(name, scene);
  54660. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54661. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54662. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54663. vertexData.applyToMesh(sphere, options.updatable);
  54664. return sphere;
  54665. };
  54666. /**
  54667. * Creates a plane polygonal mesh. By default, this is a disc.
  54668. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54669. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54670. * 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.
  54671. * 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
  54672. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54673. * 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).
  54674. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54675. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54676. */
  54677. MeshBuilder.CreateDisc = function (name, options, scene) {
  54678. if (scene === void 0) { scene = null; }
  54679. var disc = new BABYLON.Mesh(name, scene);
  54680. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54681. disc._originalBuilderSideOrientation = options.sideOrientation;
  54682. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54683. vertexData.applyToMesh(disc, options.updatable);
  54684. return disc;
  54685. };
  54686. /**
  54687. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54688. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54689. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54690. * 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`).
  54691. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54692. * 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.
  54693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54694. * 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).
  54695. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54697. */
  54698. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54699. var sphere = new BABYLON.Mesh(name, scene);
  54700. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54701. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54702. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54703. vertexData.applyToMesh(sphere, options.updatable);
  54704. return sphere;
  54705. };
  54706. ;
  54707. /**
  54708. * Creates a ribbon mesh.
  54709. * 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.
  54710. *
  54711. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54712. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54713. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54714. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54715. * 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.
  54716. * 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.
  54717. * 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
  54718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54719. * 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).
  54720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54721. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54722. * 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.
  54723. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54724. * 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
  54725. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54726. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54728. */
  54729. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54730. if (scene === void 0) { scene = null; }
  54731. var pathArray = options.pathArray;
  54732. var closeArray = options.closeArray;
  54733. var closePath = options.closePath;
  54734. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54735. var instance = options.instance;
  54736. var updatable = options.updatable;
  54737. if (instance) {
  54738. // positionFunction : ribbon case
  54739. // only pathArray and sideOrientation parameters are taken into account for positions update
  54740. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54741. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54742. var positionFunction = function (positions) {
  54743. var minlg = pathArray[0].length;
  54744. var i = 0;
  54745. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54746. for (var si = 1; si <= ns; si++) {
  54747. for (var p = 0; p < pathArray.length; p++) {
  54748. var path = pathArray[p];
  54749. var l = path.length;
  54750. minlg = (minlg < l) ? minlg : l;
  54751. var j = 0;
  54752. while (j < minlg) {
  54753. positions[i] = path[j].x;
  54754. positions[i + 1] = path[j].y;
  54755. positions[i + 2] = path[j].z;
  54756. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54757. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54758. }
  54759. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54760. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54761. }
  54762. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54763. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54764. }
  54765. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54766. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54767. }
  54768. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54769. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54770. }
  54771. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54772. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54773. }
  54774. j++;
  54775. i += 3;
  54776. }
  54777. if (instance._closePath) {
  54778. positions[i] = path[0].x;
  54779. positions[i + 1] = path[0].y;
  54780. positions[i + 2] = path[0].z;
  54781. i += 3;
  54782. }
  54783. }
  54784. }
  54785. };
  54786. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54787. positionFunction(positions);
  54788. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54789. instance._boundingInfo.update(instance._worldMatrix);
  54790. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54791. if (options.colors) {
  54792. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54793. for (var c = 0; c < options.colors.length; c++) {
  54794. colors[c * 4] = options.colors[c].r;
  54795. colors[c * 4 + 1] = options.colors[c].g;
  54796. colors[c * 4 + 2] = options.colors[c].b;
  54797. colors[c * 4 + 3] = options.colors[c].a;
  54798. }
  54799. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54800. }
  54801. if (options.uvs) {
  54802. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54803. for (var i = 0; i < options.uvs.length; i++) {
  54804. uvs[i * 2] = options.uvs[i].x;
  54805. uvs[i * 2 + 1] = options.uvs[i].y;
  54806. }
  54807. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54808. }
  54809. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54810. var indices = instance.getIndices();
  54811. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54812. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54813. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54814. if (instance._closePath) {
  54815. var indexFirst = 0;
  54816. var indexLast = 0;
  54817. for (var p = 0; p < pathArray.length; p++) {
  54818. indexFirst = instance._idx[p] * 3;
  54819. if (p + 1 < pathArray.length) {
  54820. indexLast = (instance._idx[p + 1] - 1) * 3;
  54821. }
  54822. else {
  54823. indexLast = normals.length - 3;
  54824. }
  54825. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54826. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54827. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54828. normals[indexLast] = normals[indexFirst];
  54829. normals[indexLast + 1] = normals[indexFirst + 1];
  54830. normals[indexLast + 2] = normals[indexFirst + 2];
  54831. }
  54832. }
  54833. if (!(instance.areNormalsFrozen)) {
  54834. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54835. }
  54836. }
  54837. return instance;
  54838. }
  54839. else {
  54840. var ribbon = new BABYLON.Mesh(name, scene);
  54841. ribbon._originalBuilderSideOrientation = sideOrientation;
  54842. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54843. if (closePath) {
  54844. ribbon._idx = vertexData._idx;
  54845. }
  54846. ribbon._closePath = closePath;
  54847. ribbon._closeArray = closeArray;
  54848. vertexData.applyToMesh(ribbon, updatable);
  54849. return ribbon;
  54850. }
  54851. };
  54852. /**
  54853. * Creates a cylinder or a cone mesh.
  54854. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54855. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54856. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54857. * 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.
  54858. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54859. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54860. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54861. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54862. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54863. * 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).
  54864. * 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
  54865. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54866. * 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
  54867. * 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.
  54868. * If `enclose` is false, a ring surface is one element.
  54869. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54870. * 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
  54871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54872. * 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).
  54873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54875. */
  54876. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54877. var cylinder = new BABYLON.Mesh(name, scene);
  54878. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54879. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54880. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54881. vertexData.applyToMesh(cylinder, options.updatable);
  54882. return cylinder;
  54883. };
  54884. /**
  54885. * Creates a torus mesh.
  54886. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54887. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54888. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54889. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54890. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54891. * 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).
  54892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54894. */
  54895. MeshBuilder.CreateTorus = function (name, options, scene) {
  54896. var torus = new BABYLON.Mesh(name, scene);
  54897. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54898. torus._originalBuilderSideOrientation = options.sideOrientation;
  54899. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54900. vertexData.applyToMesh(torus, options.updatable);
  54901. return torus;
  54902. };
  54903. /**
  54904. * Creates a torus knot mesh.
  54905. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54906. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54907. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54908. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54909. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54911. * 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).
  54912. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54914. */
  54915. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54916. var torusKnot = new BABYLON.Mesh(name, scene);
  54917. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54918. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54919. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54920. vertexData.applyToMesh(torusKnot, options.updatable);
  54921. return torusKnot;
  54922. };
  54923. /**
  54924. * Creates a line system mesh.
  54925. * A line system is a pool of many lines gathered in a single mesh.
  54926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54927. * 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.
  54928. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54929. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54930. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  54931. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54932. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54933. * 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
  54934. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54936. */
  54937. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54938. var instance = options.instance;
  54939. var lines = options.lines;
  54940. var colors = options.colors;
  54941. if (instance) {
  54942. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54943. var vertexColor;
  54944. var lineColors;
  54945. if (colors) {
  54946. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54947. }
  54948. var i = 0;
  54949. var c = 0;
  54950. for (var l = 0; l < lines.length; l++) {
  54951. var points = lines[l];
  54952. for (var p = 0; p < points.length; p++) {
  54953. positions[i] = points[p].x;
  54954. positions[i + 1] = points[p].y;
  54955. positions[i + 2] = points[p].z;
  54956. if (colors && vertexColor) {
  54957. lineColors = colors[l];
  54958. vertexColor[c] = lineColors[p].r;
  54959. vertexColor[c + 1] = lineColors[p].g;
  54960. vertexColor[c + 2] = lineColors[p].b;
  54961. vertexColor[c + 3] = lineColors[p].a;
  54962. c += 4;
  54963. }
  54964. i += 3;
  54965. }
  54966. }
  54967. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54968. if (colors && vertexColor) {
  54969. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54970. }
  54971. return instance;
  54972. }
  54973. // line system creation
  54974. var useVertexColor = (colors) ? true : false;
  54975. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54976. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54977. vertexData.applyToMesh(lineSystem, options.updatable);
  54978. return lineSystem;
  54979. };
  54980. /**
  54981. * Creates a line mesh.
  54982. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54983. * 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.
  54984. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54985. * The parameter `points` is an array successive Vector3.
  54986. * 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
  54987. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54988. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54989. * When updating an instance, remember that only point positions can change, not the number of points.
  54990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54991. */
  54992. MeshBuilder.CreateLines = function (name, options, scene) {
  54993. if (scene === void 0) { scene = null; }
  54994. var colors = (options.colors) ? [options.colors] : null;
  54995. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54996. return lines;
  54997. };
  54998. /**
  54999. * Creates a dashed line mesh.
  55000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55001. * 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.
  55002. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55003. * The parameter `points` is an array successive Vector3.
  55004. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55005. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55006. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55007. * 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
  55008. * When updating an instance, remember that only point positions can change, not the number of points.
  55009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55010. */
  55011. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55012. if (scene === void 0) { scene = null; }
  55013. var points = options.points;
  55014. var instance = options.instance;
  55015. var gapSize = options.gapSize || 1;
  55016. var dashSize = options.dashSize || 3;
  55017. if (instance) {
  55018. var positionFunction = function (positions) {
  55019. var curvect = BABYLON.Vector3.Zero();
  55020. var nbSeg = positions.length / 6;
  55021. var lg = 0;
  55022. var nb = 0;
  55023. var shft = 0;
  55024. var dashshft = 0;
  55025. var curshft = 0;
  55026. var p = 0;
  55027. var i = 0;
  55028. var j = 0;
  55029. for (i = 0; i < points.length - 1; i++) {
  55030. points[i + 1].subtractToRef(points[i], curvect);
  55031. lg += curvect.length();
  55032. }
  55033. shft = lg / nbSeg;
  55034. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55035. for (i = 0; i < points.length - 1; i++) {
  55036. points[i + 1].subtractToRef(points[i], curvect);
  55037. nb = Math.floor(curvect.length() / shft);
  55038. curvect.normalize();
  55039. j = 0;
  55040. while (j < nb && p < positions.length) {
  55041. curshft = shft * j;
  55042. positions[p] = points[i].x + curshft * curvect.x;
  55043. positions[p + 1] = points[i].y + curshft * curvect.y;
  55044. positions[p + 2] = points[i].z + curshft * curvect.z;
  55045. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55046. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55047. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55048. p += 6;
  55049. j++;
  55050. }
  55051. }
  55052. while (p < positions.length) {
  55053. positions[p] = points[i].x;
  55054. positions[p + 1] = points[i].y;
  55055. positions[p + 2] = points[i].z;
  55056. p += 3;
  55057. }
  55058. };
  55059. instance.updateMeshPositions(positionFunction, false);
  55060. return instance;
  55061. }
  55062. // dashed lines creation
  55063. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55064. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55065. vertexData.applyToMesh(dashedLines, options.updatable);
  55066. dashedLines.dashSize = dashSize;
  55067. dashedLines.gapSize = gapSize;
  55068. return dashedLines;
  55069. };
  55070. /**
  55071. * Creates an extruded shape mesh.
  55072. * 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.
  55073. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55074. *
  55075. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55076. * 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
  55077. * extruded along the Z axis.
  55078. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55079. * 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.
  55080. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55081. * 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
  55082. * 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
  55083. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55085. * 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).
  55086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55087. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55089. */
  55090. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55091. if (scene === void 0) { scene = null; }
  55092. var path = options.path;
  55093. var shape = options.shape;
  55094. var scale = options.scale || 1;
  55095. var rotation = options.rotation || 0;
  55096. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55097. var updatable = options.updatable;
  55098. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55099. var instance = options.instance || null;
  55100. var invertUV = options.invertUV || false;
  55101. 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);
  55102. };
  55103. /**
  55104. * Creates an custom extruded shape mesh.
  55105. * 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.
  55106. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55107. *
  55108. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55109. * 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
  55110. * extruded along the Z axis.
  55111. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55112. * 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
  55113. * and the distance of this point from the begining of the path :
  55114. * ```javascript
  55115. * var rotationFunction = function(i, distance) {
  55116. * // do things
  55117. * return rotationValue; }
  55118. * ```
  55119. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55120. * 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
  55121. * and the distance of this point from the begining of the path :
  55122. * ```javascript
  55123. * var scaleFunction = function(i, distance) {
  55124. * // do things
  55125. * return scaleValue;}
  55126. * ```
  55127. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55128. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55129. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55130. * 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
  55131. * 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
  55132. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55133. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55134. * 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).
  55135. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55136. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55138. */
  55139. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55140. var path = options.path;
  55141. var shape = options.shape;
  55142. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55143. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55144. var ribbonCloseArray = options.ribbonCloseArray || false;
  55145. var ribbonClosePath = options.ribbonClosePath || false;
  55146. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55147. var updatable = options.updatable;
  55148. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55149. var instance = options.instance;
  55150. var invertUV = options.invertUV || false;
  55151. 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);
  55152. };
  55153. /**
  55154. * Creates lathe mesh.
  55155. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55156. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55157. *
  55158. * 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
  55159. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55160. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55161. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55162. * 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.
  55163. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55164. * 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
  55165. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55166. * 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).
  55167. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55168. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55170. */
  55171. MeshBuilder.CreateLathe = function (name, options, scene) {
  55172. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55173. var closed = (options.closed === undefined) ? true : options.closed;
  55174. var shape = options.shape;
  55175. var radius = options.radius || 1;
  55176. var tessellation = options.tessellation || 64;
  55177. var updatable = options.updatable;
  55178. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55179. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55180. var pi2 = Math.PI * 2;
  55181. var paths = new Array();
  55182. var invertUV = options.invertUV || false;
  55183. var i = 0;
  55184. var p = 0;
  55185. var step = pi2 / tessellation * arc;
  55186. var rotated;
  55187. var path = new Array();
  55188. ;
  55189. for (i = 0; i <= tessellation; i++) {
  55190. var path = [];
  55191. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55192. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55193. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55194. }
  55195. for (p = 0; p < shape.length; p++) {
  55196. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55197. path.push(rotated);
  55198. }
  55199. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55200. 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));
  55201. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55202. }
  55203. paths.push(path);
  55204. }
  55205. // lathe ribbon
  55206. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55207. return lathe;
  55208. };
  55209. /**
  55210. * Creates a plane mesh.
  55211. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55212. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55213. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55214. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55216. * 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).
  55217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55219. */
  55220. MeshBuilder.CreatePlane = function (name, options, scene) {
  55221. var plane = new BABYLON.Mesh(name, scene);
  55222. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55223. plane._originalBuilderSideOrientation = options.sideOrientation;
  55224. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55225. vertexData.applyToMesh(plane, options.updatable);
  55226. if (options.sourcePlane) {
  55227. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55228. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55229. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55230. plane.rotate(vectorProduct, product);
  55231. }
  55232. return plane;
  55233. };
  55234. /**
  55235. * Creates a ground mesh.
  55236. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55237. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55238. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55240. */
  55241. MeshBuilder.CreateGround = function (name, options, scene) {
  55242. var ground = new BABYLON.GroundMesh(name, scene);
  55243. ground._setReady(false);
  55244. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55245. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55246. ground._width = options.width || 1;
  55247. ground._height = options.height || 1;
  55248. ground._maxX = ground._width / 2;
  55249. ground._maxZ = ground._height / 2;
  55250. ground._minX = -ground._maxX;
  55251. ground._minZ = -ground._maxZ;
  55252. var vertexData = BABYLON.VertexData.CreateGround(options);
  55253. vertexData.applyToMesh(ground, options.updatable);
  55254. ground._setReady(true);
  55255. return ground;
  55256. };
  55257. /**
  55258. * Creates a tiled ground mesh.
  55259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55260. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55261. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55262. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55263. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55264. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55265. * numbers of subdivisions on the ground width and height of each tile.
  55266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55267. */
  55268. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55269. var tiledGround = new BABYLON.Mesh(name, scene);
  55270. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55271. vertexData.applyToMesh(tiledGround, options.updatable);
  55272. return tiledGround;
  55273. };
  55274. /**
  55275. * Creates a ground mesh from a height map.
  55276. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55278. * The parameter `url` sets the URL of the height map image resource.
  55279. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55280. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55281. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55282. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55283. * 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.
  55284. * 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).
  55285. * This function is passed the newly built mesh :
  55286. * ```javascript
  55287. * function(mesh) { // do things
  55288. * return; }
  55289. * ```
  55290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55291. */
  55292. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55293. var width = options.width || 10.0;
  55294. var height = options.height || 10.0;
  55295. var subdivisions = options.subdivisions || 1 | 0;
  55296. var minHeight = options.minHeight || 0.0;
  55297. var maxHeight = options.maxHeight || 1.0;
  55298. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55299. var updatable = options.updatable;
  55300. var onReady = options.onReady;
  55301. var ground = new BABYLON.GroundMesh(name, scene);
  55302. ground._subdivisionsX = subdivisions;
  55303. ground._subdivisionsY = subdivisions;
  55304. ground._width = width;
  55305. ground._height = height;
  55306. ground._maxX = ground._width / 2.0;
  55307. ground._maxZ = ground._height / 2.0;
  55308. ground._minX = -ground._maxX;
  55309. ground._minZ = -ground._maxZ;
  55310. ground._setReady(false);
  55311. var onload = function (img) {
  55312. // Getting height map data
  55313. var canvas = document.createElement("canvas");
  55314. var context = canvas.getContext("2d");
  55315. if (!context) {
  55316. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55317. }
  55318. if (scene.isDisposed) {
  55319. return;
  55320. }
  55321. var bufferWidth = img.width;
  55322. var bufferHeight = img.height;
  55323. canvas.width = bufferWidth;
  55324. canvas.height = bufferHeight;
  55325. context.drawImage(img, 0, 0);
  55326. // Create VertexData from map data
  55327. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55328. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55329. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55330. width: width, height: height,
  55331. subdivisions: subdivisions,
  55332. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55333. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55334. });
  55335. vertexData.applyToMesh(ground, updatable);
  55336. ground._setReady(true);
  55337. //execute ready callback, if set
  55338. if (onReady) {
  55339. onReady(ground);
  55340. }
  55341. };
  55342. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55343. return ground;
  55344. };
  55345. /**
  55346. * Creates a polygon mesh.
  55347. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55348. * 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.
  55349. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55351. * 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).
  55352. * Remember you can only change the shape positions, not their number when updating a polygon.
  55353. */
  55354. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55355. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55356. var shape = options.shape;
  55357. var holes = options.holes || [];
  55358. var depth = options.depth || 0;
  55359. var contours = [];
  55360. var hole = [];
  55361. for (var i = 0; i < shape.length; i++) {
  55362. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55363. }
  55364. var epsilon = 0.00000001;
  55365. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55366. contours.pop();
  55367. }
  55368. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55369. for (var hNb = 0; hNb < holes.length; hNb++) {
  55370. hole = [];
  55371. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55372. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55373. }
  55374. polygonTriangulation.addHole(hole);
  55375. }
  55376. var polygon = polygonTriangulation.build(options.updatable, depth);
  55377. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55378. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55379. vertexData.applyToMesh(polygon, options.updatable);
  55380. return polygon;
  55381. };
  55382. ;
  55383. /**
  55384. * Creates an extruded polygon mesh, with depth in the Y direction.
  55385. * 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).
  55386. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55387. */
  55388. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55389. return MeshBuilder.CreatePolygon(name, options, scene);
  55390. };
  55391. ;
  55392. /**
  55393. * Creates a tube mesh.
  55394. * 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.
  55395. *
  55396. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55397. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55398. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55399. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55400. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55401. * 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.
  55402. * It must return a radius value (positive float) :
  55403. * ```javascript
  55404. * var radiusFunction = function(i, distance) {
  55405. * // do things
  55406. * return radius; }
  55407. * ```
  55408. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55409. * 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
  55410. * 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
  55411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55412. * 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).
  55413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55414. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55416. */
  55417. MeshBuilder.CreateTube = function (name, options, scene) {
  55418. var path = options.path;
  55419. var instance = options.instance;
  55420. var radius = 1.0;
  55421. if (instance) {
  55422. radius = instance.radius;
  55423. }
  55424. if (options.radius !== undefined) {
  55425. radius = options.radius;
  55426. }
  55427. ;
  55428. var tessellation = options.tessellation || 64 | 0;
  55429. var radiusFunction = options.radiusFunction || null;
  55430. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55431. var invertUV = options.invertUV || false;
  55432. var updatable = options.updatable;
  55433. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55434. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55435. // tube geometry
  55436. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55437. var tangents = path3D.getTangents();
  55438. var normals = path3D.getNormals();
  55439. var distances = path3D.getDistances();
  55440. var pi2 = Math.PI * 2;
  55441. var step = pi2 / tessellation * arc;
  55442. var returnRadius = function () { return radius; };
  55443. var radiusFunctionFinal = radiusFunction || returnRadius;
  55444. var circlePath;
  55445. var rad;
  55446. var normal;
  55447. var rotated;
  55448. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55449. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55450. for (var i = 0; i < path.length; i++) {
  55451. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55452. circlePath = Array(); // current circle array
  55453. normal = normals[i]; // current normal
  55454. for (var t = 0; t < tessellation; t++) {
  55455. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55456. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55457. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55458. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55459. circlePath[t] = rotated;
  55460. }
  55461. circlePaths[index] = circlePath;
  55462. index++;
  55463. }
  55464. // cap
  55465. var capPath = function (nbPoints, pathIndex) {
  55466. var pointCap = Array();
  55467. for (var i = 0; i < nbPoints; i++) {
  55468. pointCap.push(path[pathIndex]);
  55469. }
  55470. return pointCap;
  55471. };
  55472. switch (cap) {
  55473. case BABYLON.Mesh.NO_CAP:
  55474. break;
  55475. case BABYLON.Mesh.CAP_START:
  55476. circlePaths[0] = capPath(tessellation, 0);
  55477. circlePaths[1] = circlePaths[2].slice(0);
  55478. break;
  55479. case BABYLON.Mesh.CAP_END:
  55480. circlePaths[index] = circlePaths[index - 1].slice(0);
  55481. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55482. break;
  55483. case BABYLON.Mesh.CAP_ALL:
  55484. circlePaths[0] = capPath(tessellation, 0);
  55485. circlePaths[1] = circlePaths[2].slice(0);
  55486. circlePaths[index] = circlePaths[index - 1].slice(0);
  55487. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55488. break;
  55489. default:
  55490. break;
  55491. }
  55492. return circlePaths;
  55493. };
  55494. var path3D;
  55495. var pathArray;
  55496. if (instance) {
  55497. var arc = options.arc || instance.arc;
  55498. path3D = (instance.path3D).update(path);
  55499. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55500. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55501. instance.path3D = path3D;
  55502. instance.pathArray = pathArray;
  55503. instance.arc = arc;
  55504. instance.radius = radius;
  55505. return instance;
  55506. }
  55507. // tube creation
  55508. path3D = new BABYLON.Path3D(path);
  55509. var newPathArray = new Array();
  55510. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55511. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55512. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55513. tube.pathArray = pathArray;
  55514. tube.path3D = path3D;
  55515. tube.tessellation = tessellation;
  55516. tube.cap = cap;
  55517. tube.arc = options.arc;
  55518. tube.radius = radius;
  55519. return tube;
  55520. };
  55521. /**
  55522. * Creates a polyhedron mesh.
  55523. *
  55524. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55525. * 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
  55526. * to choose the wanted type.
  55527. * The parameter `size` (positive float, default 1) sets the polygon size.
  55528. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55529. * 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`.
  55530. * 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
  55531. * 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)`).
  55532. * 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
  55533. * 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.
  55534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55535. * 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).
  55536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55538. */
  55539. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55540. var polyhedron = new BABYLON.Mesh(name, scene);
  55541. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55542. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55543. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55544. vertexData.applyToMesh(polyhedron, options.updatable);
  55545. return polyhedron;
  55546. };
  55547. /**
  55548. * Creates a decal mesh.
  55549. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55550. * 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.
  55551. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55552. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55553. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55554. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55555. */
  55556. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55557. var indices = sourceMesh.getIndices();
  55558. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55559. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55560. var position = options.position || BABYLON.Vector3.Zero();
  55561. var normal = options.normal || BABYLON.Vector3.Up();
  55562. var size = options.size || BABYLON.Vector3.One();
  55563. var angle = options.angle || 0;
  55564. // Getting correct rotation
  55565. if (!normal) {
  55566. var target = new BABYLON.Vector3(0, 0, 1);
  55567. var camera = sourceMesh.getScene().activeCamera;
  55568. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55569. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55570. }
  55571. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55572. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55573. var pitch = Math.atan2(normal.y, len);
  55574. // Matrix
  55575. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55576. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55577. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55578. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55579. var vertexData = new BABYLON.VertexData();
  55580. vertexData.indices = [];
  55581. vertexData.positions = [];
  55582. vertexData.normals = [];
  55583. vertexData.uvs = [];
  55584. var currentVertexDataIndex = 0;
  55585. var extractDecalVector3 = function (indexId) {
  55586. var result = new BABYLON.PositionNormalVertex();
  55587. if (!indices || !positions || !normals) {
  55588. return result;
  55589. }
  55590. var vertexId = indices[indexId];
  55591. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55592. // Send vector to decal local world
  55593. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55594. // Get normal
  55595. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55596. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55597. return result;
  55598. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55599. var clip = function (vertices, axis) {
  55600. if (vertices.length === 0) {
  55601. return vertices;
  55602. }
  55603. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55604. var clipVertices = function (v0, v1) {
  55605. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55606. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55607. };
  55608. var result = new Array();
  55609. for (var index = 0; index < vertices.length; index += 3) {
  55610. var v1Out;
  55611. var v2Out;
  55612. var v3Out;
  55613. var total = 0;
  55614. var nV1 = null;
  55615. var nV2 = null;
  55616. var nV3 = null;
  55617. var nV4 = null;
  55618. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55619. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55620. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55621. v1Out = d1 > 0;
  55622. v2Out = d2 > 0;
  55623. v3Out = d3 > 0;
  55624. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55625. switch (total) {
  55626. case 0:
  55627. result.push(vertices[index]);
  55628. result.push(vertices[index + 1]);
  55629. result.push(vertices[index + 2]);
  55630. break;
  55631. case 1:
  55632. if (v1Out) {
  55633. nV1 = vertices[index + 1];
  55634. nV2 = vertices[index + 2];
  55635. nV3 = clipVertices(vertices[index], nV1);
  55636. nV4 = clipVertices(vertices[index], nV2);
  55637. }
  55638. if (v2Out) {
  55639. nV1 = vertices[index];
  55640. nV2 = vertices[index + 2];
  55641. nV3 = clipVertices(vertices[index + 1], nV1);
  55642. nV4 = clipVertices(vertices[index + 1], nV2);
  55643. result.push(nV3);
  55644. result.push(nV2.clone());
  55645. result.push(nV1.clone());
  55646. result.push(nV2.clone());
  55647. result.push(nV3.clone());
  55648. result.push(nV4);
  55649. break;
  55650. }
  55651. if (v3Out) {
  55652. nV1 = vertices[index];
  55653. nV2 = vertices[index + 1];
  55654. nV3 = clipVertices(vertices[index + 2], nV1);
  55655. nV4 = clipVertices(vertices[index + 2], nV2);
  55656. }
  55657. if (nV1 && nV2 && nV3 && nV4) {
  55658. result.push(nV1.clone());
  55659. result.push(nV2.clone());
  55660. result.push(nV3);
  55661. result.push(nV4);
  55662. result.push(nV3.clone());
  55663. result.push(nV2.clone());
  55664. }
  55665. break;
  55666. case 2:
  55667. if (!v1Out) {
  55668. nV1 = vertices[index].clone();
  55669. nV2 = clipVertices(nV1, vertices[index + 1]);
  55670. nV3 = clipVertices(nV1, vertices[index + 2]);
  55671. result.push(nV1);
  55672. result.push(nV2);
  55673. result.push(nV3);
  55674. }
  55675. if (!v2Out) {
  55676. nV1 = vertices[index + 1].clone();
  55677. nV2 = clipVertices(nV1, vertices[index + 2]);
  55678. nV3 = clipVertices(nV1, vertices[index]);
  55679. result.push(nV1);
  55680. result.push(nV2);
  55681. result.push(nV3);
  55682. }
  55683. if (!v3Out) {
  55684. nV1 = vertices[index + 2].clone();
  55685. nV2 = clipVertices(nV1, vertices[index]);
  55686. nV3 = clipVertices(nV1, vertices[index + 1]);
  55687. result.push(nV1);
  55688. result.push(nV2);
  55689. result.push(nV3);
  55690. }
  55691. break;
  55692. case 3:
  55693. break;
  55694. }
  55695. }
  55696. return result;
  55697. };
  55698. for (var index = 0; index < indices.length; index += 3) {
  55699. var faceVertices = new Array();
  55700. faceVertices.push(extractDecalVector3(index));
  55701. faceVertices.push(extractDecalVector3(index + 1));
  55702. faceVertices.push(extractDecalVector3(index + 2));
  55703. // Clip
  55704. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55705. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55706. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55707. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55708. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55709. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55710. if (faceVertices.length === 0) {
  55711. continue;
  55712. }
  55713. // Add UVs and get back to world
  55714. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55715. var vertex = faceVertices[vIndex];
  55716. //TODO check for Int32Array | Uint32Array | Uint16Array
  55717. vertexData.indices.push(currentVertexDataIndex);
  55718. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55719. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55720. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55721. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55722. currentVertexDataIndex++;
  55723. }
  55724. }
  55725. // Return mesh
  55726. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55727. vertexData.applyToMesh(decal);
  55728. decal.position = position.clone();
  55729. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55730. return decal;
  55731. };
  55732. // Privates
  55733. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55734. // extrusion geometry
  55735. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55736. var tangents = path3D.getTangents();
  55737. var normals = path3D.getNormals();
  55738. var binormals = path3D.getBinormals();
  55739. var distances = path3D.getDistances();
  55740. var angle = 0;
  55741. var returnScale = function () { return scale !== null ? scale : 1; };
  55742. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55743. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55744. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55745. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55746. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55747. for (var i = 0; i < curve.length; i++) {
  55748. var shapePath = new Array();
  55749. var angleStep = rotate(i, distances[i]);
  55750. var scaleRatio = scl(i, distances[i]);
  55751. for (var p = 0; p < shape.length; p++) {
  55752. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55753. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55754. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55755. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55756. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55757. shapePath[p] = rotated;
  55758. }
  55759. shapePaths[index] = shapePath;
  55760. angle += angleStep;
  55761. index++;
  55762. }
  55763. // cap
  55764. var capPath = function (shapePath) {
  55765. var pointCap = Array();
  55766. var barycenter = BABYLON.Vector3.Zero();
  55767. var i;
  55768. for (i = 0; i < shapePath.length; i++) {
  55769. barycenter.addInPlace(shapePath[i]);
  55770. }
  55771. barycenter.scaleInPlace(1.0 / shapePath.length);
  55772. for (i = 0; i < shapePath.length; i++) {
  55773. pointCap.push(barycenter);
  55774. }
  55775. return pointCap;
  55776. };
  55777. switch (cap) {
  55778. case BABYLON.Mesh.NO_CAP:
  55779. break;
  55780. case BABYLON.Mesh.CAP_START:
  55781. shapePaths[0] = capPath(shapePaths[2]);
  55782. shapePaths[1] = shapePaths[2];
  55783. break;
  55784. case BABYLON.Mesh.CAP_END:
  55785. shapePaths[index] = shapePaths[index - 1];
  55786. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55787. break;
  55788. case BABYLON.Mesh.CAP_ALL:
  55789. shapePaths[0] = capPath(shapePaths[2]);
  55790. shapePaths[1] = shapePaths[2];
  55791. shapePaths[index] = shapePaths[index - 1];
  55792. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55793. break;
  55794. default:
  55795. break;
  55796. }
  55797. return shapePaths;
  55798. };
  55799. var path3D;
  55800. var pathArray;
  55801. if (instance) {
  55802. path3D = (instance.path3D).update(curve);
  55803. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55804. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55805. return instance;
  55806. }
  55807. // extruded shape creation
  55808. path3D = new BABYLON.Path3D(curve);
  55809. var newShapePaths = new Array();
  55810. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55811. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55812. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55813. extrudedGeneric.pathArray = pathArray;
  55814. extrudedGeneric.path3D = path3D;
  55815. extrudedGeneric.cap = cap;
  55816. return extrudedGeneric;
  55817. };
  55818. return MeshBuilder;
  55819. }());
  55820. BABYLON.MeshBuilder = MeshBuilder;
  55821. })(BABYLON || (BABYLON = {}));
  55822. //# sourceMappingURL=babylon.meshBuilder.js.map
  55823. var BABYLON;
  55824. (function (BABYLON) {
  55825. /**
  55826. * Draco compression (https://google.github.io/draco/)
  55827. */
  55828. var DracoCompression = /** @class */ (function () {
  55829. /**
  55830. * Constructor
  55831. * @param numWorkers The number of workers for async operations
  55832. */
  55833. function DracoCompression(numWorkers) {
  55834. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55835. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55836. if (!workerBlobUrl || !Worker) {
  55837. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  55838. return;
  55839. }
  55840. var workers = new Array(numWorkers);
  55841. for (var i = 0; i < workers.length; i++) {
  55842. var worker = new Worker(workerBlobUrl);
  55843. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55844. workers[i] = worker;
  55845. }
  55846. this._workerPool = new BABYLON.WorkerPool(workers);
  55847. }
  55848. /**
  55849. * Stop all async operations and release resources.
  55850. */
  55851. DracoCompression.prototype.dispose = function () {
  55852. this._workerPool.dispose();
  55853. delete this._workerPool;
  55854. };
  55855. /**
  55856. * Decode Draco compressed mesh data to vertex data.
  55857. * @param data The array buffer view for the Draco compression data
  55858. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55859. * @returns A promise that resolves with the decoded vertex data
  55860. */
  55861. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55862. var _this = this;
  55863. return new Promise(function (resolve, reject) {
  55864. _this._workerPool.push(function (worker, onComplete) {
  55865. var vertexData = new BABYLON.VertexData();
  55866. var onError = function (error) {
  55867. worker.removeEventListener("error", onError);
  55868. worker.removeEventListener("message", onMessage);
  55869. reject(error);
  55870. onComplete();
  55871. };
  55872. var onMessage = function (message) {
  55873. if (message.data === "done") {
  55874. worker.removeEventListener("error", onError);
  55875. worker.removeEventListener("message", onMessage);
  55876. resolve(vertexData);
  55877. onComplete();
  55878. }
  55879. else if (message.data.id === "indices") {
  55880. vertexData.indices = message.data.value;
  55881. }
  55882. else {
  55883. vertexData.set(message.data.value, message.data.id);
  55884. }
  55885. };
  55886. worker.addEventListener("error", onError);
  55887. worker.addEventListener("message", onMessage);
  55888. var dataCopy = new Uint8Array(data.byteLength);
  55889. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55890. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55891. });
  55892. });
  55893. };
  55894. /**
  55895. * The worker function that gets converted to a blob url to pass into a worker.
  55896. */
  55897. DracoCompression._Worker = function () {
  55898. // self is actually a DedicatedWorkerGlobalScope
  55899. var _self = self;
  55900. var decodeMesh = function (data, attributes) {
  55901. var dracoModule = new DracoDecoderModule();
  55902. var buffer = new dracoModule.DecoderBuffer();
  55903. buffer.Init(data, data.byteLength);
  55904. var decoder = new dracoModule.Decoder();
  55905. var geometry;
  55906. var status;
  55907. try {
  55908. var type = decoder.GetEncodedGeometryType(buffer);
  55909. switch (type) {
  55910. case dracoModule.TRIANGULAR_MESH:
  55911. geometry = new dracoModule.Mesh();
  55912. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55913. break;
  55914. case dracoModule.POINT_CLOUD:
  55915. geometry = new dracoModule.PointCloud();
  55916. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55917. break;
  55918. default:
  55919. throw new Error("Invalid geometry type " + type);
  55920. }
  55921. if (!status.ok() || !geometry.ptr) {
  55922. throw new Error(status.error_msg());
  55923. }
  55924. var numPoints = geometry.num_points();
  55925. if (type === dracoModule.TRIANGULAR_MESH) {
  55926. var numFaces = geometry.num_faces();
  55927. var faceIndices = new dracoModule.DracoInt32Array();
  55928. try {
  55929. var indices = new Uint32Array(numFaces * 3);
  55930. for (var i = 0; i < numFaces; i++) {
  55931. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55932. var offset = i * 3;
  55933. indices[offset + 0] = faceIndices.GetValue(0);
  55934. indices[offset + 1] = faceIndices.GetValue(1);
  55935. indices[offset + 2] = faceIndices.GetValue(2);
  55936. }
  55937. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55938. }
  55939. finally {
  55940. dracoModule.destroy(faceIndices);
  55941. }
  55942. }
  55943. for (var kind in attributes) {
  55944. var uniqueId = attributes[kind];
  55945. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55946. var dracoData = new dracoModule.DracoFloat32Array();
  55947. try {
  55948. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55949. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55950. for (var i = 0; i < babylonData.length; i++) {
  55951. babylonData[i] = dracoData.GetValue(i);
  55952. }
  55953. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55954. }
  55955. finally {
  55956. dracoModule.destroy(dracoData);
  55957. }
  55958. }
  55959. }
  55960. finally {
  55961. if (geometry) {
  55962. dracoModule.destroy(geometry);
  55963. }
  55964. dracoModule.destroy(decoder);
  55965. dracoModule.destroy(buffer);
  55966. }
  55967. _self.postMessage("done");
  55968. };
  55969. _self.onmessage = function (event) {
  55970. switch (event.data.id) {
  55971. case "initDecoder": {
  55972. importScripts(event.data.url);
  55973. break;
  55974. }
  55975. case "decodeMesh": {
  55976. decodeMesh(event.data.data, event.data.attributes);
  55977. break;
  55978. }
  55979. }
  55980. };
  55981. };
  55982. DracoCompression._GetDefaultDecoderUrl = function () {
  55983. for (var i = 0; i < document.scripts.length; i++) {
  55984. if (document.scripts[i].type === "text/x-draco-decoder") {
  55985. return document.scripts[i].src;
  55986. }
  55987. }
  55988. return null;
  55989. };
  55990. /**
  55991. * Gets the url to the draco decoder if available.
  55992. */
  55993. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  55994. return DracoCompression;
  55995. }());
  55996. BABYLON.DracoCompression = DracoCompression;
  55997. })(BABYLON || (BABYLON = {}));
  55998. //# sourceMappingURL=babylon.dracoCompression.js.map
  55999. var BABYLON;
  56000. (function (BABYLON) {
  56001. var AudioEngine = /** @class */ (function () {
  56002. function AudioEngine() {
  56003. this._audioContext = null;
  56004. this._audioContextInitialized = false;
  56005. this.canUseWebAudio = false;
  56006. this.WarnedWebAudioUnsupported = false;
  56007. this.unlocked = false;
  56008. this.isMP3supported = false;
  56009. this.isOGGsupported = false;
  56010. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56011. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56012. this.canUseWebAudio = true;
  56013. }
  56014. var audioElem = document.createElement('audio');
  56015. try {
  56016. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56017. this.isMP3supported = true;
  56018. }
  56019. }
  56020. catch (e) {
  56021. // protect error during capability check.
  56022. }
  56023. try {
  56024. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56025. this.isOGGsupported = true;
  56026. }
  56027. }
  56028. catch (e) {
  56029. // protect error during capability check.
  56030. }
  56031. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56032. this._unlockiOSaudio();
  56033. }
  56034. else {
  56035. this.unlocked = true;
  56036. }
  56037. }
  56038. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56039. get: function () {
  56040. if (!this._audioContextInitialized) {
  56041. this._initializeAudioContext();
  56042. }
  56043. return this._audioContext;
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. AudioEngine.prototype._unlockiOSaudio = function () {
  56049. var _this = this;
  56050. var unlockaudio = function () {
  56051. if (!_this.audioContext) {
  56052. return;
  56053. }
  56054. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56055. var source = _this.audioContext.createBufferSource();
  56056. source.buffer = buffer;
  56057. source.connect(_this.audioContext.destination);
  56058. source.start(0);
  56059. setTimeout(function () {
  56060. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56061. _this.unlocked = true;
  56062. window.removeEventListener('touchend', unlockaudio, false);
  56063. if (_this.onAudioUnlocked) {
  56064. _this.onAudioUnlocked();
  56065. }
  56066. }
  56067. }, 0);
  56068. };
  56069. window.addEventListener('touchend', unlockaudio, false);
  56070. };
  56071. AudioEngine.prototype._initializeAudioContext = function () {
  56072. try {
  56073. if (this.canUseWebAudio) {
  56074. this._audioContext = new AudioContext();
  56075. // create a global volume gain node
  56076. this.masterGain = this._audioContext.createGain();
  56077. this.masterGain.gain.value = 1;
  56078. this.masterGain.connect(this._audioContext.destination);
  56079. this._audioContextInitialized = true;
  56080. }
  56081. }
  56082. catch (e) {
  56083. this.canUseWebAudio = false;
  56084. BABYLON.Tools.Error("Web Audio: " + e.message);
  56085. }
  56086. };
  56087. AudioEngine.prototype.dispose = function () {
  56088. if (this.canUseWebAudio && this._audioContextInitialized) {
  56089. if (this._connectedAnalyser && this._audioContext) {
  56090. this._connectedAnalyser.stopDebugCanvas();
  56091. this._connectedAnalyser.dispose();
  56092. this.masterGain.disconnect();
  56093. this.masterGain.connect(this._audioContext.destination);
  56094. this._connectedAnalyser = null;
  56095. }
  56096. this.masterGain.gain.value = 1;
  56097. }
  56098. this.WarnedWebAudioUnsupported = false;
  56099. };
  56100. AudioEngine.prototype.getGlobalVolume = function () {
  56101. if (this.canUseWebAudio && this._audioContextInitialized) {
  56102. return this.masterGain.gain.value;
  56103. }
  56104. else {
  56105. return -1;
  56106. }
  56107. };
  56108. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56109. if (this.canUseWebAudio && this._audioContextInitialized) {
  56110. this.masterGain.gain.value = newVolume;
  56111. }
  56112. };
  56113. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56114. if (this._connectedAnalyser) {
  56115. this._connectedAnalyser.stopDebugCanvas();
  56116. }
  56117. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56118. this._connectedAnalyser = analyser;
  56119. this.masterGain.disconnect();
  56120. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56121. }
  56122. };
  56123. return AudioEngine;
  56124. }());
  56125. BABYLON.AudioEngine = AudioEngine;
  56126. })(BABYLON || (BABYLON = {}));
  56127. //# sourceMappingURL=babylon.audioEngine.js.map
  56128. var BABYLON;
  56129. (function (BABYLON) {
  56130. var Sound = /** @class */ (function () {
  56131. /**
  56132. * Create a sound and attach it to a scene
  56133. * @param name Name of your sound
  56134. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56135. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56136. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56137. */
  56138. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56139. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56140. var _this = this;
  56141. this.autoplay = false;
  56142. this.loop = false;
  56143. this.useCustomAttenuation = false;
  56144. this.spatialSound = false;
  56145. this.refDistance = 1;
  56146. this.rolloffFactor = 1;
  56147. this.maxDistance = 100;
  56148. this.distanceModel = "linear";
  56149. this._panningModel = "equalpower";
  56150. this._playbackRate = 1;
  56151. this._streaming = false;
  56152. this._startTime = 0;
  56153. this._startOffset = 0;
  56154. this._position = BABYLON.Vector3.Zero();
  56155. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56156. this._volume = 1;
  56157. this._isReadyToPlay = false;
  56158. this.isPlaying = false;
  56159. this.isPaused = false;
  56160. this._isDirectional = false;
  56161. // Used if you'd like to create a directional sound.
  56162. // If not set, the sound will be omnidirectional
  56163. this._coneInnerAngle = 360;
  56164. this._coneOuterAngle = 360;
  56165. this._coneOuterGain = 0;
  56166. this._isOutputConnected = false;
  56167. this._urlType = "Unknown";
  56168. this.name = name;
  56169. this._scene = scene;
  56170. this._readyToPlayCallback = readyToPlayCallback;
  56171. // Default custom attenuation function is a linear attenuation
  56172. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56173. if (currentDistance < maxDistance) {
  56174. return currentVolume * (1 - currentDistance / maxDistance);
  56175. }
  56176. else {
  56177. return 0;
  56178. }
  56179. };
  56180. if (options) {
  56181. this.autoplay = options.autoplay || false;
  56182. this.loop = options.loop || false;
  56183. // if volume === 0, we need another way to check this option
  56184. if (options.volume !== undefined) {
  56185. this._volume = options.volume;
  56186. }
  56187. this.spatialSound = options.spatialSound || false;
  56188. this.maxDistance = options.maxDistance || 100;
  56189. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56190. this.rolloffFactor = options.rolloffFactor || 1;
  56191. this.refDistance = options.refDistance || 1;
  56192. this.distanceModel = options.distanceModel || "linear";
  56193. this._playbackRate = options.playbackRate || 1;
  56194. this._streaming = options.streaming || false;
  56195. }
  56196. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56197. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56198. this._soundGain.gain.value = this._volume;
  56199. this._inputAudioNode = this._soundGain;
  56200. this._ouputAudioNode = this._soundGain;
  56201. if (this.spatialSound) {
  56202. this._createSpatialParameters();
  56203. }
  56204. this._scene.mainSoundTrack.AddSound(this);
  56205. var validParameter = true;
  56206. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56207. if (urlOrArrayBuffer) {
  56208. if (typeof (urlOrArrayBuffer) === "string")
  56209. this._urlType = "String";
  56210. if (Array.isArray(urlOrArrayBuffer))
  56211. this._urlType = "Array";
  56212. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56213. this._urlType = "ArrayBuffer";
  56214. var urls = [];
  56215. var codecSupportedFound = false;
  56216. switch (this._urlType) {
  56217. case "ArrayBuffer":
  56218. if (urlOrArrayBuffer.byteLength > 0) {
  56219. codecSupportedFound = true;
  56220. this._soundLoaded(urlOrArrayBuffer);
  56221. }
  56222. break;
  56223. case "String":
  56224. urls.push(urlOrArrayBuffer);
  56225. case "Array":
  56226. if (urls.length === 0)
  56227. urls = urlOrArrayBuffer;
  56228. // If we found a supported format, we load it immediately and stop the loop
  56229. for (var i = 0; i < urls.length; i++) {
  56230. var url = urls[i];
  56231. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56232. codecSupportedFound = true;
  56233. }
  56234. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56235. codecSupportedFound = true;
  56236. }
  56237. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56238. codecSupportedFound = true;
  56239. }
  56240. if (url.indexOf("blob:") !== -1) {
  56241. codecSupportedFound = true;
  56242. }
  56243. if (codecSupportedFound) {
  56244. // Loading sound using XHR2
  56245. if (!this._streaming) {
  56246. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56247. }
  56248. else {
  56249. this._htmlAudioElement = new Audio(url);
  56250. this._htmlAudioElement.controls = false;
  56251. this._htmlAudioElement.loop = this.loop;
  56252. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56253. this._htmlAudioElement.preload = "auto";
  56254. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56255. _this._isReadyToPlay = true;
  56256. if (_this.autoplay) {
  56257. _this.play();
  56258. }
  56259. if (_this._readyToPlayCallback) {
  56260. _this._readyToPlayCallback();
  56261. }
  56262. });
  56263. document.body.appendChild(this._htmlAudioElement);
  56264. }
  56265. break;
  56266. }
  56267. }
  56268. break;
  56269. default:
  56270. validParameter = false;
  56271. break;
  56272. }
  56273. if (!validParameter) {
  56274. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56275. }
  56276. else {
  56277. if (!codecSupportedFound) {
  56278. this._isReadyToPlay = true;
  56279. // Simulating a ready to play event to avoid breaking code path
  56280. if (this._readyToPlayCallback) {
  56281. window.setTimeout(function () {
  56282. if (_this._readyToPlayCallback) {
  56283. _this._readyToPlayCallback();
  56284. }
  56285. }, 1000);
  56286. }
  56287. }
  56288. }
  56289. }
  56290. }
  56291. else {
  56292. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56293. this._scene.mainSoundTrack.AddSound(this);
  56294. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56295. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56296. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56297. }
  56298. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56299. if (this._readyToPlayCallback) {
  56300. window.setTimeout(function () {
  56301. if (_this._readyToPlayCallback) {
  56302. _this._readyToPlayCallback();
  56303. }
  56304. }, 1000);
  56305. }
  56306. }
  56307. }
  56308. Sound.prototype.dispose = function () {
  56309. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56310. if (this.isPlaying) {
  56311. this.stop();
  56312. }
  56313. this._isReadyToPlay = false;
  56314. if (this.soundTrackId === -1) {
  56315. this._scene.mainSoundTrack.RemoveSound(this);
  56316. }
  56317. else {
  56318. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56319. }
  56320. if (this._soundGain) {
  56321. this._soundGain.disconnect();
  56322. this._soundGain = null;
  56323. }
  56324. if (this._soundPanner) {
  56325. this._soundPanner.disconnect();
  56326. this._soundPanner = null;
  56327. }
  56328. if (this._soundSource) {
  56329. this._soundSource.disconnect();
  56330. this._soundSource = null;
  56331. }
  56332. this._audioBuffer = null;
  56333. if (this._htmlAudioElement) {
  56334. this._htmlAudioElement.pause();
  56335. this._htmlAudioElement.src = "";
  56336. document.body.removeChild(this._htmlAudioElement);
  56337. }
  56338. if (this._connectedMesh && this._registerFunc) {
  56339. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56340. this._connectedMesh = null;
  56341. }
  56342. }
  56343. };
  56344. Sound.prototype.isReady = function () {
  56345. return this._isReadyToPlay;
  56346. };
  56347. Sound.prototype._soundLoaded = function (audioData) {
  56348. var _this = this;
  56349. if (!BABYLON.Engine.audioEngine.audioContext) {
  56350. return;
  56351. }
  56352. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56353. _this._audioBuffer = buffer;
  56354. _this._isReadyToPlay = true;
  56355. if (_this.autoplay) {
  56356. _this.play();
  56357. }
  56358. if (_this._readyToPlayCallback) {
  56359. _this._readyToPlayCallback();
  56360. }
  56361. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56362. };
  56363. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56364. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56365. this._audioBuffer = audioBuffer;
  56366. this._isReadyToPlay = true;
  56367. }
  56368. };
  56369. Sound.prototype.updateOptions = function (options) {
  56370. if (options) {
  56371. this.loop = options.loop || this.loop;
  56372. this.maxDistance = options.maxDistance || this.maxDistance;
  56373. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56374. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56375. this.refDistance = options.refDistance || this.refDistance;
  56376. this.distanceModel = options.distanceModel || this.distanceModel;
  56377. this._playbackRate = options.playbackRate || this._playbackRate;
  56378. this._updateSpatialParameters();
  56379. if (this.isPlaying) {
  56380. if (this._streaming) {
  56381. this._htmlAudioElement.playbackRate = this._playbackRate;
  56382. }
  56383. else {
  56384. if (this._soundSource) {
  56385. this._soundSource.playbackRate.value = this._playbackRate;
  56386. }
  56387. }
  56388. }
  56389. }
  56390. };
  56391. Sound.prototype._createSpatialParameters = function () {
  56392. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56393. if (this._scene.headphone) {
  56394. this._panningModel = "HRTF";
  56395. }
  56396. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56397. this._updateSpatialParameters();
  56398. this._soundPanner.connect(this._ouputAudioNode);
  56399. this._inputAudioNode = this._soundPanner;
  56400. }
  56401. };
  56402. Sound.prototype._updateSpatialParameters = function () {
  56403. if (this.spatialSound && this._soundPanner) {
  56404. if (this.useCustomAttenuation) {
  56405. // Tricks to disable in a way embedded Web Audio attenuation
  56406. this._soundPanner.distanceModel = "linear";
  56407. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56408. this._soundPanner.refDistance = 1;
  56409. this._soundPanner.rolloffFactor = 1;
  56410. this._soundPanner.panningModel = this._panningModel;
  56411. }
  56412. else {
  56413. this._soundPanner.distanceModel = this.distanceModel;
  56414. this._soundPanner.maxDistance = this.maxDistance;
  56415. this._soundPanner.refDistance = this.refDistance;
  56416. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56417. this._soundPanner.panningModel = this._panningModel;
  56418. }
  56419. }
  56420. };
  56421. Sound.prototype.switchPanningModelToHRTF = function () {
  56422. this._panningModel = "HRTF";
  56423. this._switchPanningModel();
  56424. };
  56425. Sound.prototype.switchPanningModelToEqualPower = function () {
  56426. this._panningModel = "equalpower";
  56427. this._switchPanningModel();
  56428. };
  56429. Sound.prototype._switchPanningModel = function () {
  56430. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56431. this._soundPanner.panningModel = this._panningModel;
  56432. }
  56433. };
  56434. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56435. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56436. if (this._isOutputConnected) {
  56437. this._ouputAudioNode.disconnect();
  56438. }
  56439. this._ouputAudioNode.connect(soundTrackAudioNode);
  56440. this._isOutputConnected = true;
  56441. }
  56442. };
  56443. /**
  56444. * Transform this sound into a directional source
  56445. * @param coneInnerAngle Size of the inner cone in degree
  56446. * @param coneOuterAngle Size of the outer cone in degree
  56447. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56448. */
  56449. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56450. if (coneOuterAngle < coneInnerAngle) {
  56451. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56452. return;
  56453. }
  56454. this._coneInnerAngle = coneInnerAngle;
  56455. this._coneOuterAngle = coneOuterAngle;
  56456. this._coneOuterGain = coneOuterGain;
  56457. this._isDirectional = true;
  56458. if (this.isPlaying && this.loop) {
  56459. this.stop();
  56460. this.play();
  56461. }
  56462. };
  56463. Sound.prototype.setPosition = function (newPosition) {
  56464. this._position = newPosition;
  56465. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56466. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56467. }
  56468. };
  56469. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56470. this._localDirection = newLocalDirection;
  56471. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56472. this._updateDirection();
  56473. }
  56474. };
  56475. Sound.prototype._updateDirection = function () {
  56476. if (!this._connectedMesh || !this._soundPanner) {
  56477. return;
  56478. }
  56479. var mat = this._connectedMesh.getWorldMatrix();
  56480. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56481. direction.normalize();
  56482. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56483. };
  56484. Sound.prototype.updateDistanceFromListener = function () {
  56485. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56486. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56487. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56488. }
  56489. };
  56490. Sound.prototype.setAttenuationFunction = function (callback) {
  56491. this._customAttenuationFunction = callback;
  56492. };
  56493. /**
  56494. * Play the sound
  56495. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56496. * @param offset (optional) Start the sound setting it at a specific time
  56497. */
  56498. Sound.prototype.play = function (time, offset) {
  56499. var _this = this;
  56500. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56501. try {
  56502. if (this._startOffset < 0) {
  56503. time = -this._startOffset;
  56504. this._startOffset = 0;
  56505. }
  56506. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56507. if (!this._soundSource || !this._streamingSource) {
  56508. if (this.spatialSound && this._soundPanner) {
  56509. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56510. if (this._isDirectional) {
  56511. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56512. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56513. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56514. if (this._connectedMesh) {
  56515. this._updateDirection();
  56516. }
  56517. else {
  56518. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56519. }
  56520. }
  56521. }
  56522. }
  56523. if (this._streaming) {
  56524. if (!this._streamingSource) {
  56525. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56526. this._htmlAudioElement.onended = function () { _this._onended(); };
  56527. this._htmlAudioElement.playbackRate = this._playbackRate;
  56528. }
  56529. this._streamingSource.disconnect();
  56530. this._streamingSource.connect(this._inputAudioNode);
  56531. this._htmlAudioElement.play();
  56532. }
  56533. else {
  56534. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56535. this._soundSource.buffer = this._audioBuffer;
  56536. this._soundSource.connect(this._inputAudioNode);
  56537. this._soundSource.loop = this.loop;
  56538. this._soundSource.playbackRate.value = this._playbackRate;
  56539. this._soundSource.onended = function () { _this._onended(); };
  56540. if (this._soundSource.buffer) {
  56541. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56542. }
  56543. }
  56544. this._startTime = startTime;
  56545. this.isPlaying = true;
  56546. this.isPaused = false;
  56547. }
  56548. catch (ex) {
  56549. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56550. }
  56551. }
  56552. };
  56553. Sound.prototype._onended = function () {
  56554. this.isPlaying = false;
  56555. if (this.onended) {
  56556. this.onended();
  56557. }
  56558. };
  56559. /**
  56560. * Stop the sound
  56561. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56562. */
  56563. Sound.prototype.stop = function (time) {
  56564. if (this.isPlaying) {
  56565. if (this._streaming) {
  56566. this._htmlAudioElement.pause();
  56567. // Test needed for Firefox or it will generate an Invalid State Error
  56568. if (this._htmlAudioElement.currentTime > 0) {
  56569. this._htmlAudioElement.currentTime = 0;
  56570. }
  56571. }
  56572. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56573. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56574. this._soundSource.stop(stopTime);
  56575. this._soundSource.onended = function () { };
  56576. if (!this.isPaused) {
  56577. this._startOffset = 0;
  56578. }
  56579. }
  56580. this.isPlaying = false;
  56581. }
  56582. };
  56583. Sound.prototype.pause = function () {
  56584. if (this.isPlaying) {
  56585. this.isPaused = true;
  56586. if (this._streaming) {
  56587. this._htmlAudioElement.pause();
  56588. }
  56589. else if (BABYLON.Engine.audioEngine.audioContext) {
  56590. this.stop(0);
  56591. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56592. }
  56593. }
  56594. };
  56595. Sound.prototype.setVolume = function (newVolume, time) {
  56596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56597. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56598. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56599. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56600. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56601. }
  56602. else {
  56603. this._soundGain.gain.value = newVolume;
  56604. }
  56605. }
  56606. this._volume = newVolume;
  56607. };
  56608. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56609. this._playbackRate = newPlaybackRate;
  56610. if (this.isPlaying) {
  56611. if (this._streaming) {
  56612. this._htmlAudioElement.playbackRate = this._playbackRate;
  56613. }
  56614. else if (this._soundSource) {
  56615. this._soundSource.playbackRate.value = this._playbackRate;
  56616. }
  56617. }
  56618. };
  56619. Sound.prototype.getVolume = function () {
  56620. return this._volume;
  56621. };
  56622. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56623. var _this = this;
  56624. if (this._connectedMesh && this._registerFunc) {
  56625. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56626. this._registerFunc = null;
  56627. }
  56628. this._connectedMesh = meshToConnectTo;
  56629. if (!this.spatialSound) {
  56630. this.spatialSound = true;
  56631. this._createSpatialParameters();
  56632. if (this.isPlaying && this.loop) {
  56633. this.stop();
  56634. this.play();
  56635. }
  56636. }
  56637. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56638. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56639. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56640. };
  56641. Sound.prototype.detachFromMesh = function () {
  56642. if (this._connectedMesh && this._registerFunc) {
  56643. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56644. this._registerFunc = null;
  56645. this._connectedMesh = null;
  56646. }
  56647. };
  56648. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56649. if (!node.getBoundingInfo) {
  56650. return;
  56651. }
  56652. var mesh = node;
  56653. var boundingInfo = mesh.getBoundingInfo();
  56654. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56655. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56656. this._updateDirection();
  56657. }
  56658. };
  56659. Sound.prototype.clone = function () {
  56660. var _this = this;
  56661. if (!this._streaming) {
  56662. var setBufferAndRun = function () {
  56663. if (_this._isReadyToPlay) {
  56664. clonedSound._audioBuffer = _this.getAudioBuffer();
  56665. clonedSound._isReadyToPlay = true;
  56666. if (clonedSound.autoplay) {
  56667. clonedSound.play();
  56668. }
  56669. }
  56670. else {
  56671. window.setTimeout(setBufferAndRun, 300);
  56672. }
  56673. };
  56674. var currentOptions = {
  56675. autoplay: this.autoplay, loop: this.loop,
  56676. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56677. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56678. refDistance: this.refDistance, distanceModel: this.distanceModel
  56679. };
  56680. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56681. if (this.useCustomAttenuation) {
  56682. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56683. }
  56684. clonedSound.setPosition(this._position);
  56685. clonedSound.setPlaybackRate(this._playbackRate);
  56686. setBufferAndRun();
  56687. return clonedSound;
  56688. }
  56689. else {
  56690. return null;
  56691. }
  56692. };
  56693. Sound.prototype.getAudioBuffer = function () {
  56694. return this._audioBuffer;
  56695. };
  56696. Sound.prototype.serialize = function () {
  56697. var serializationObject = {
  56698. name: this.name,
  56699. url: this.name,
  56700. autoplay: this.autoplay,
  56701. loop: this.loop,
  56702. volume: this._volume,
  56703. spatialSound: this.spatialSound,
  56704. maxDistance: this.maxDistance,
  56705. rolloffFactor: this.rolloffFactor,
  56706. refDistance: this.refDistance,
  56707. distanceModel: this.distanceModel,
  56708. playbackRate: this._playbackRate,
  56709. panningModel: this._panningModel,
  56710. soundTrackId: this.soundTrackId
  56711. };
  56712. if (this.spatialSound) {
  56713. if (this._connectedMesh)
  56714. serializationObject.connectedMeshId = this._connectedMesh.id;
  56715. serializationObject.position = this._position.asArray();
  56716. serializationObject.refDistance = this.refDistance;
  56717. serializationObject.distanceModel = this.distanceModel;
  56718. serializationObject.isDirectional = this._isDirectional;
  56719. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56720. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56721. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56722. serializationObject.coneOuterGain = this._coneOuterGain;
  56723. }
  56724. return serializationObject;
  56725. };
  56726. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56727. var soundName = parsedSound.name;
  56728. var soundUrl;
  56729. if (parsedSound.url) {
  56730. soundUrl = rootUrl + parsedSound.url;
  56731. }
  56732. else {
  56733. soundUrl = rootUrl + soundName;
  56734. }
  56735. var options = {
  56736. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56737. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56738. rolloffFactor: parsedSound.rolloffFactor,
  56739. refDistance: parsedSound.refDistance,
  56740. distanceModel: parsedSound.distanceModel,
  56741. playbackRate: parsedSound.playbackRate
  56742. };
  56743. var newSound;
  56744. if (!sourceSound) {
  56745. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56746. scene._addPendingData(newSound);
  56747. }
  56748. else {
  56749. var setBufferAndRun = function () {
  56750. if (sourceSound._isReadyToPlay) {
  56751. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56752. newSound._isReadyToPlay = true;
  56753. if (newSound.autoplay) {
  56754. newSound.play();
  56755. }
  56756. }
  56757. else {
  56758. window.setTimeout(setBufferAndRun, 300);
  56759. }
  56760. };
  56761. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56762. setBufferAndRun();
  56763. }
  56764. if (parsedSound.position) {
  56765. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56766. newSound.setPosition(soundPosition);
  56767. }
  56768. if (parsedSound.isDirectional) {
  56769. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56770. if (parsedSound.localDirectionToMesh) {
  56771. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56772. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56773. }
  56774. }
  56775. if (parsedSound.connectedMeshId) {
  56776. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56777. if (connectedMesh) {
  56778. newSound.attachToMesh(connectedMesh);
  56779. }
  56780. }
  56781. return newSound;
  56782. };
  56783. return Sound;
  56784. }());
  56785. BABYLON.Sound = Sound;
  56786. })(BABYLON || (BABYLON = {}));
  56787. //# sourceMappingURL=babylon.sound.js.map
  56788. var BABYLON;
  56789. (function (BABYLON) {
  56790. var SoundTrack = /** @class */ (function () {
  56791. function SoundTrack(scene, options) {
  56792. this.id = -1;
  56793. this._isMainTrack = false;
  56794. this._isInitialized = false;
  56795. this._scene = scene;
  56796. this.soundCollection = new Array();
  56797. this._options = options;
  56798. if (!this._isMainTrack) {
  56799. this._scene.soundTracks.push(this);
  56800. this.id = this._scene.soundTracks.length - 1;
  56801. }
  56802. }
  56803. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56804. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56805. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56806. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56807. if (this._options) {
  56808. if (this._options.volume) {
  56809. this._outputAudioNode.gain.value = this._options.volume;
  56810. }
  56811. if (this._options.mainTrack) {
  56812. this._isMainTrack = this._options.mainTrack;
  56813. }
  56814. }
  56815. this._isInitialized = true;
  56816. }
  56817. };
  56818. SoundTrack.prototype.dispose = function () {
  56819. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56820. if (this._connectedAnalyser) {
  56821. this._connectedAnalyser.stopDebugCanvas();
  56822. }
  56823. while (this.soundCollection.length) {
  56824. this.soundCollection[0].dispose();
  56825. }
  56826. if (this._outputAudioNode) {
  56827. this._outputAudioNode.disconnect();
  56828. }
  56829. this._outputAudioNode = null;
  56830. }
  56831. };
  56832. SoundTrack.prototype.AddSound = function (sound) {
  56833. if (!this._isInitialized) {
  56834. this._initializeSoundTrackAudioGraph();
  56835. }
  56836. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56837. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56838. }
  56839. if (sound.soundTrackId) {
  56840. if (sound.soundTrackId === -1) {
  56841. this._scene.mainSoundTrack.RemoveSound(sound);
  56842. }
  56843. else {
  56844. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56845. }
  56846. }
  56847. this.soundCollection.push(sound);
  56848. sound.soundTrackId = this.id;
  56849. };
  56850. SoundTrack.prototype.RemoveSound = function (sound) {
  56851. var index = this.soundCollection.indexOf(sound);
  56852. if (index !== -1) {
  56853. this.soundCollection.splice(index, 1);
  56854. }
  56855. };
  56856. SoundTrack.prototype.setVolume = function (newVolume) {
  56857. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56858. this._outputAudioNode.gain.value = newVolume;
  56859. }
  56860. };
  56861. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56862. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56863. for (var i = 0; i < this.soundCollection.length; i++) {
  56864. this.soundCollection[i].switchPanningModelToHRTF();
  56865. }
  56866. }
  56867. };
  56868. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56869. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56870. for (var i = 0; i < this.soundCollection.length; i++) {
  56871. this.soundCollection[i].switchPanningModelToEqualPower();
  56872. }
  56873. }
  56874. };
  56875. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56876. if (this._connectedAnalyser) {
  56877. this._connectedAnalyser.stopDebugCanvas();
  56878. }
  56879. this._connectedAnalyser = analyser;
  56880. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56881. this._outputAudioNode.disconnect();
  56882. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56883. }
  56884. };
  56885. return SoundTrack;
  56886. }());
  56887. BABYLON.SoundTrack = SoundTrack;
  56888. })(BABYLON || (BABYLON = {}));
  56889. //# sourceMappingURL=babylon.soundtrack.js.map
  56890. var BABYLON;
  56891. (function (BABYLON) {
  56892. var Analyser = /** @class */ (function () {
  56893. function Analyser(scene) {
  56894. this.SMOOTHING = 0.75;
  56895. this.FFT_SIZE = 512;
  56896. this.BARGRAPHAMPLITUDE = 256;
  56897. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56898. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56899. this._scene = scene;
  56900. this._audioEngine = BABYLON.Engine.audioEngine;
  56901. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56902. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56903. this._webAudioAnalyser.minDecibels = -140;
  56904. this._webAudioAnalyser.maxDecibels = 0;
  56905. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56906. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56907. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56908. }
  56909. }
  56910. Analyser.prototype.getFrequencyBinCount = function () {
  56911. if (this._audioEngine.canUseWebAudio) {
  56912. return this._webAudioAnalyser.frequencyBinCount;
  56913. }
  56914. else {
  56915. return 0;
  56916. }
  56917. };
  56918. Analyser.prototype.getByteFrequencyData = function () {
  56919. if (this._audioEngine.canUseWebAudio) {
  56920. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56921. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56922. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56923. }
  56924. return this._byteFreqs;
  56925. };
  56926. Analyser.prototype.getByteTimeDomainData = function () {
  56927. if (this._audioEngine.canUseWebAudio) {
  56928. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56929. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56930. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56931. }
  56932. return this._byteTime;
  56933. };
  56934. Analyser.prototype.getFloatFrequencyData = function () {
  56935. if (this._audioEngine.canUseWebAudio) {
  56936. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56937. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56938. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56939. }
  56940. return this._floatFreqs;
  56941. };
  56942. Analyser.prototype.drawDebugCanvas = function () {
  56943. var _this = this;
  56944. if (this._audioEngine.canUseWebAudio) {
  56945. if (!this._debugCanvas) {
  56946. this._debugCanvas = document.createElement("canvas");
  56947. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56948. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56949. this._debugCanvas.style.position = "absolute";
  56950. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56951. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56952. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56953. document.body.appendChild(this._debugCanvas);
  56954. this._registerFunc = function () {
  56955. _this.drawDebugCanvas();
  56956. };
  56957. this._scene.registerBeforeRender(this._registerFunc);
  56958. }
  56959. if (this._registerFunc && this._debugCanvasContext) {
  56960. var workingArray = this.getByteFrequencyData();
  56961. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56962. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56963. // Draw the frequency domain chart.
  56964. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56965. var value = workingArray[i];
  56966. var percent = value / this.BARGRAPHAMPLITUDE;
  56967. var height = this.DEBUGCANVASSIZE.height * percent;
  56968. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56969. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56970. var hue = i / this.getFrequencyBinCount() * 360;
  56971. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56972. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56973. }
  56974. }
  56975. }
  56976. };
  56977. Analyser.prototype.stopDebugCanvas = function () {
  56978. if (this._debugCanvas) {
  56979. if (this._registerFunc) {
  56980. this._scene.unregisterBeforeRender(this._registerFunc);
  56981. this._registerFunc = null;
  56982. }
  56983. document.body.removeChild(this._debugCanvas);
  56984. this._debugCanvas = null;
  56985. this._debugCanvasContext = null;
  56986. }
  56987. };
  56988. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56989. if (this._audioEngine.canUseWebAudio) {
  56990. inputAudioNode.connect(this._webAudioAnalyser);
  56991. this._webAudioAnalyser.connect(outputAudioNode);
  56992. }
  56993. };
  56994. Analyser.prototype.dispose = function () {
  56995. if (this._audioEngine.canUseWebAudio) {
  56996. this._webAudioAnalyser.disconnect();
  56997. }
  56998. };
  56999. return Analyser;
  57000. }());
  57001. BABYLON.Analyser = Analyser;
  57002. })(BABYLON || (BABYLON = {}));
  57003. //# sourceMappingURL=babylon.analyser.js.map
  57004. var BABYLON;
  57005. (function (BABYLON) {
  57006. var CubeTexture = /** @class */ (function (_super) {
  57007. __extends(CubeTexture, _super);
  57008. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57009. if (extensions === void 0) { extensions = null; }
  57010. if (noMipmap === void 0) { noMipmap = false; }
  57011. if (files === void 0) { files = null; }
  57012. if (onLoad === void 0) { onLoad = null; }
  57013. if (onError === void 0) { onError = null; }
  57014. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57015. if (prefiltered === void 0) { prefiltered = false; }
  57016. if (forcedExtension === void 0) { forcedExtension = null; }
  57017. var _this = _super.call(this, scene) || this;
  57018. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57019. /**
  57020. * Gets or sets the center of the bounding box associated with the cube texture
  57021. * It must define where the camera used to render the texture was set
  57022. */
  57023. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57024. _this.name = rootUrl;
  57025. _this.url = rootUrl;
  57026. _this._noMipmap = noMipmap;
  57027. _this.hasAlpha = false;
  57028. _this._format = format;
  57029. _this._prefiltered = prefiltered;
  57030. _this.isCube = true;
  57031. _this._textureMatrix = BABYLON.Matrix.Identity();
  57032. if (prefiltered) {
  57033. _this.gammaSpace = false;
  57034. }
  57035. if (!rootUrl && !files) {
  57036. return _this;
  57037. }
  57038. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57039. var lastDot = rootUrl.lastIndexOf(".");
  57040. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57041. var isDDS = (extension === ".dds");
  57042. if (!files) {
  57043. if (!isDDS && !extensions) {
  57044. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57045. }
  57046. files = [];
  57047. if (extensions) {
  57048. for (var index = 0; index < extensions.length; index++) {
  57049. files.push(rootUrl + extensions[index]);
  57050. }
  57051. }
  57052. }
  57053. _this._files = files;
  57054. if (!_this._texture) {
  57055. if (!scene.useDelayedTextureLoading) {
  57056. if (prefiltered) {
  57057. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57058. }
  57059. else {
  57060. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57061. }
  57062. }
  57063. else {
  57064. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57065. }
  57066. }
  57067. else if (onLoad) {
  57068. if (_this._texture.isReady) {
  57069. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57070. }
  57071. else {
  57072. _this._texture.onLoadedObservable.add(onLoad);
  57073. }
  57074. }
  57075. return _this;
  57076. }
  57077. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57078. get: function () {
  57079. return this._boundingBoxSize;
  57080. },
  57081. /**
  57082. * Gets or sets the size of the bounding box associated with the cube texture
  57083. * When defined, the cubemap will switch to local mode
  57084. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57085. * @example https://www.babylonjs-playground.com/#RNASML
  57086. */
  57087. set: function (value) {
  57088. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57089. return;
  57090. }
  57091. this._boundingBoxSize = value;
  57092. var scene = this.getScene();
  57093. if (scene) {
  57094. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57095. }
  57096. },
  57097. enumerable: true,
  57098. configurable: true
  57099. });
  57100. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57101. var rootUrlKey = "";
  57102. files.forEach(function (url) { return rootUrlKey += url; });
  57103. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57104. };
  57105. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57106. if (forcedExtension === void 0) { forcedExtension = null; }
  57107. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57108. };
  57109. // Methods
  57110. CubeTexture.prototype.delayLoad = function () {
  57111. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57112. return;
  57113. }
  57114. var scene = this.getScene();
  57115. if (!scene) {
  57116. return;
  57117. }
  57118. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57119. this._texture = this._getFromCache(this.url, this._noMipmap);
  57120. if (!this._texture) {
  57121. if (this._prefiltered) {
  57122. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57123. }
  57124. else {
  57125. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57126. }
  57127. }
  57128. };
  57129. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57130. return this._textureMatrix;
  57131. };
  57132. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57133. this._textureMatrix = value;
  57134. };
  57135. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57136. var texture = BABYLON.SerializationHelper.Parse(function () {
  57137. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57138. }, parsedTexture, scene);
  57139. // Local Cubemaps
  57140. if (parsedTexture.boundingBoxPosition) {
  57141. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57142. }
  57143. if (parsedTexture.boundingBoxSize) {
  57144. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57145. }
  57146. // Animations
  57147. if (parsedTexture.animations) {
  57148. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57149. var parsedAnimation = parsedTexture.animations[animationIndex];
  57150. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57151. }
  57152. }
  57153. return texture;
  57154. };
  57155. CubeTexture.prototype.clone = function () {
  57156. var _this = this;
  57157. return BABYLON.SerializationHelper.Clone(function () {
  57158. var scene = _this.getScene();
  57159. if (!scene) {
  57160. return _this;
  57161. }
  57162. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57163. }, this);
  57164. };
  57165. return CubeTexture;
  57166. }(BABYLON.BaseTexture));
  57167. BABYLON.CubeTexture = CubeTexture;
  57168. })(BABYLON || (BABYLON = {}));
  57169. //# sourceMappingURL=babylon.cubeTexture.js.map
  57170. var BABYLON;
  57171. (function (BABYLON) {
  57172. var RenderTargetTexture = /** @class */ (function (_super) {
  57173. __extends(RenderTargetTexture, _super);
  57174. /**
  57175. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57176. * or used a shadow, depth texture...
  57177. * @param name The friendly name of the texture
  57178. * @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)
  57179. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57180. * @param generateMipMaps True if mip maps need to be generated after render.
  57181. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57182. * @param type The type of the buffer in the RTT (int, half float, float...)
  57183. * @param isCube True if a cube texture needs to be created
  57184. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57185. * @param generateDepthBuffer True to generate a depth buffer
  57186. * @param generateStencilBuffer True to generate a stencil buffer
  57187. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57188. */
  57189. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57190. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57191. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57192. if (isCube === void 0) { isCube = false; }
  57193. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57194. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57195. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57196. if (isMulti === void 0) { isMulti = false; }
  57197. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57198. _this.isCube = isCube;
  57199. /**
  57200. * Use this list to define the list of mesh you want to render.
  57201. */
  57202. _this.renderList = new Array();
  57203. _this.renderParticles = true;
  57204. _this.renderSprites = false;
  57205. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57206. _this.ignoreCameraViewport = false;
  57207. // Events
  57208. /**
  57209. * An event triggered when the texture is unbind.
  57210. * @type {BABYLON.Observable}
  57211. */
  57212. _this.onBeforeBindObservable = new BABYLON.Observable();
  57213. /**
  57214. * An event triggered when the texture is unbind.
  57215. * @type {BABYLON.Observable}
  57216. */
  57217. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57218. /**
  57219. * An event triggered before rendering the texture
  57220. * @type {BABYLON.Observable}
  57221. */
  57222. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57223. /**
  57224. * An event triggered after rendering the texture
  57225. * @type {BABYLON.Observable}
  57226. */
  57227. _this.onAfterRenderObservable = new BABYLON.Observable();
  57228. /**
  57229. * An event triggered after the texture clear
  57230. * @type {BABYLON.Observable}
  57231. */
  57232. _this.onClearObservable = new BABYLON.Observable();
  57233. _this._currentRefreshId = -1;
  57234. _this._refreshRate = 1;
  57235. _this._samples = 1;
  57236. /**
  57237. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57238. * It must define where the camera used to render the texture is set
  57239. */
  57240. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57241. scene = _this.getScene();
  57242. if (!scene) {
  57243. return _this;
  57244. }
  57245. _this._engine = scene.getEngine();
  57246. _this.name = name;
  57247. _this.isRenderTarget = true;
  57248. _this._initialSizeParameter = size;
  57249. _this._processSizeParameter(size);
  57250. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57251. });
  57252. _this._generateMipMaps = generateMipMaps ? true : false;
  57253. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57254. // Rendering groups
  57255. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57256. if (isMulti) {
  57257. return _this;
  57258. }
  57259. _this._renderTargetOptions = {
  57260. generateMipMaps: generateMipMaps,
  57261. type: type,
  57262. samplingMode: samplingMode,
  57263. generateDepthBuffer: generateDepthBuffer,
  57264. generateStencilBuffer: generateStencilBuffer
  57265. };
  57266. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57267. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57268. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57269. }
  57270. if (isCube) {
  57271. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57272. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57273. _this._textureMatrix = BABYLON.Matrix.Identity();
  57274. }
  57275. else {
  57276. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57277. }
  57278. return _this;
  57279. }
  57280. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57281. get: function () {
  57282. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57283. },
  57284. enumerable: true,
  57285. configurable: true
  57286. });
  57287. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57288. get: function () {
  57289. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57290. },
  57291. enumerable: true,
  57292. configurable: true
  57293. });
  57294. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57295. get: function () {
  57296. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57297. },
  57298. enumerable: true,
  57299. configurable: true
  57300. });
  57301. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57302. set: function (callback) {
  57303. if (this._onAfterUnbindObserver) {
  57304. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57305. }
  57306. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57307. },
  57308. enumerable: true,
  57309. configurable: true
  57310. });
  57311. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57312. set: function (callback) {
  57313. if (this._onBeforeRenderObserver) {
  57314. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57315. }
  57316. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57317. },
  57318. enumerable: true,
  57319. configurable: true
  57320. });
  57321. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57322. set: function (callback) {
  57323. if (this._onAfterRenderObserver) {
  57324. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57325. }
  57326. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57327. },
  57328. enumerable: true,
  57329. configurable: true
  57330. });
  57331. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57332. set: function (callback) {
  57333. if (this._onClearObserver) {
  57334. this.onClearObservable.remove(this._onClearObserver);
  57335. }
  57336. this._onClearObserver = this.onClearObservable.add(callback);
  57337. },
  57338. enumerable: true,
  57339. configurable: true
  57340. });
  57341. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57342. get: function () {
  57343. return this._renderTargetOptions;
  57344. },
  57345. enumerable: true,
  57346. configurable: true
  57347. });
  57348. RenderTargetTexture.prototype._onRatioRescale = function () {
  57349. if (this._sizeRatio) {
  57350. this.resize(this._initialSizeParameter);
  57351. }
  57352. };
  57353. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57354. get: function () {
  57355. return this._boundingBoxSize;
  57356. },
  57357. /**
  57358. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57359. * When defined, the cubemap will switch to local mode
  57360. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57361. * @example https://www.babylonjs-playground.com/#RNASML
  57362. */
  57363. set: function (value) {
  57364. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57365. return;
  57366. }
  57367. this._boundingBoxSize = value;
  57368. var scene = this.getScene();
  57369. if (scene) {
  57370. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57371. }
  57372. },
  57373. enumerable: true,
  57374. configurable: true
  57375. });
  57376. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57377. if (size.ratio) {
  57378. this._sizeRatio = size.ratio;
  57379. this._size = {
  57380. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57381. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57382. };
  57383. }
  57384. else {
  57385. this._size = size;
  57386. }
  57387. };
  57388. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57389. get: function () {
  57390. return this._samples;
  57391. },
  57392. set: function (value) {
  57393. if (this._samples === value) {
  57394. return;
  57395. }
  57396. var scene = this.getScene();
  57397. if (!scene) {
  57398. return;
  57399. }
  57400. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57406. this._currentRefreshId = -1;
  57407. };
  57408. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57409. get: function () {
  57410. return this._refreshRate;
  57411. },
  57412. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57413. set: function (value) {
  57414. this._refreshRate = value;
  57415. this.resetRefreshCounter();
  57416. },
  57417. enumerable: true,
  57418. configurable: true
  57419. });
  57420. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57421. if (!this._postProcessManager) {
  57422. var scene = this.getScene();
  57423. if (!scene) {
  57424. return;
  57425. }
  57426. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57427. this._postProcesses = new Array();
  57428. }
  57429. this._postProcesses.push(postProcess);
  57430. this._postProcesses[0].autoClear = false;
  57431. };
  57432. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57433. if (!this._postProcesses) {
  57434. return;
  57435. }
  57436. if (dispose) {
  57437. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57438. var postProcess = _a[_i];
  57439. postProcess.dispose();
  57440. }
  57441. }
  57442. this._postProcesses = [];
  57443. };
  57444. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57445. if (!this._postProcesses) {
  57446. return;
  57447. }
  57448. var index = this._postProcesses.indexOf(postProcess);
  57449. if (index === -1) {
  57450. return;
  57451. }
  57452. this._postProcesses.splice(index, 1);
  57453. if (this._postProcesses.length > 0) {
  57454. this._postProcesses[0].autoClear = false;
  57455. }
  57456. };
  57457. RenderTargetTexture.prototype._shouldRender = function () {
  57458. if (this._currentRefreshId === -1) {
  57459. this._currentRefreshId = 1;
  57460. return true;
  57461. }
  57462. if (this.refreshRate === this._currentRefreshId) {
  57463. this._currentRefreshId = 1;
  57464. return true;
  57465. }
  57466. this._currentRefreshId++;
  57467. return false;
  57468. };
  57469. RenderTargetTexture.prototype.getRenderSize = function () {
  57470. if (this._size.width) {
  57471. return this._size.width;
  57472. }
  57473. return this._size;
  57474. };
  57475. RenderTargetTexture.prototype.getRenderWidth = function () {
  57476. if (this._size.width) {
  57477. return this._size.width;
  57478. }
  57479. return this._size;
  57480. };
  57481. RenderTargetTexture.prototype.getRenderHeight = function () {
  57482. if (this._size.width) {
  57483. return this._size.height;
  57484. }
  57485. return this._size;
  57486. };
  57487. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57488. get: function () {
  57489. return true;
  57490. },
  57491. enumerable: true,
  57492. configurable: true
  57493. });
  57494. RenderTargetTexture.prototype.scale = function (ratio) {
  57495. var newSize = this.getRenderSize() * ratio;
  57496. this.resize(newSize);
  57497. };
  57498. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57499. if (this.isCube) {
  57500. return this._textureMatrix;
  57501. }
  57502. return _super.prototype.getReflectionTextureMatrix.call(this);
  57503. };
  57504. RenderTargetTexture.prototype.resize = function (size) {
  57505. this.releaseInternalTexture();
  57506. var scene = this.getScene();
  57507. if (!scene) {
  57508. return;
  57509. }
  57510. this._processSizeParameter(size);
  57511. if (this.isCube) {
  57512. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57513. }
  57514. else {
  57515. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57516. }
  57517. };
  57518. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57519. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57520. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57521. var scene = this.getScene();
  57522. if (!scene) {
  57523. return;
  57524. }
  57525. var engine = scene.getEngine();
  57526. if (this.useCameraPostProcesses !== undefined) {
  57527. useCameraPostProcess = this.useCameraPostProcesses;
  57528. }
  57529. if (this._waitingRenderList) {
  57530. this.renderList = [];
  57531. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57532. var id = this._waitingRenderList[index];
  57533. var mesh_1 = scene.getMeshByID(id);
  57534. if (mesh_1) {
  57535. this.renderList.push(mesh_1);
  57536. }
  57537. }
  57538. delete this._waitingRenderList;
  57539. }
  57540. // Is predicate defined?
  57541. if (this.renderListPredicate) {
  57542. if (this.renderList) {
  57543. this.renderList.splice(0); // Clear previous renderList
  57544. }
  57545. else {
  57546. this.renderList = [];
  57547. }
  57548. var scene = this.getScene();
  57549. if (!scene) {
  57550. return;
  57551. }
  57552. var sceneMeshes = scene.meshes;
  57553. for (var index = 0; index < sceneMeshes.length; index++) {
  57554. var mesh = sceneMeshes[index];
  57555. if (this.renderListPredicate(mesh)) {
  57556. this.renderList.push(mesh);
  57557. }
  57558. }
  57559. }
  57560. this.onBeforeBindObservable.notifyObservers(this);
  57561. // Set custom projection.
  57562. // Needs to be before binding to prevent changing the aspect ratio.
  57563. var camera;
  57564. if (this.activeCamera) {
  57565. camera = this.activeCamera;
  57566. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57567. if (this.activeCamera !== scene.activeCamera) {
  57568. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57569. }
  57570. }
  57571. else {
  57572. camera = scene.activeCamera;
  57573. if (camera) {
  57574. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57575. }
  57576. }
  57577. // Prepare renderingManager
  57578. this._renderingManager.reset();
  57579. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57580. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57581. var sceneRenderId = scene.getRenderId();
  57582. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57583. var mesh = currentRenderList[meshIndex];
  57584. if (mesh) {
  57585. if (!mesh.isReady()) {
  57586. // Reset _currentRefreshId
  57587. this.resetRefreshCounter();
  57588. continue;
  57589. }
  57590. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57591. var isMasked = void 0;
  57592. if (!this.renderList && camera) {
  57593. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57594. }
  57595. else {
  57596. isMasked = false;
  57597. }
  57598. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57599. mesh._activate(sceneRenderId);
  57600. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57601. var subMesh = mesh.subMeshes[subIndex];
  57602. scene._activeIndices.addCount(subMesh.indexCount, false);
  57603. this._renderingManager.dispatch(subMesh, mesh);
  57604. }
  57605. }
  57606. }
  57607. }
  57608. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57609. var particleSystem = scene.particleSystems[particleIndex];
  57610. var emitter = particleSystem.emitter;
  57611. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57612. continue;
  57613. }
  57614. if (currentRenderList.indexOf(emitter) >= 0) {
  57615. this._renderingManager.dispatchParticles(particleSystem);
  57616. }
  57617. }
  57618. if (this.isCube) {
  57619. for (var face = 0; face < 6; face++) {
  57620. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57621. scene.incrementRenderId();
  57622. scene.resetCachedMaterial();
  57623. }
  57624. }
  57625. else {
  57626. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57627. }
  57628. this.onAfterUnbindObservable.notifyObservers(this);
  57629. if (scene.activeCamera) {
  57630. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57631. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57632. }
  57633. engine.setViewport(scene.activeCamera.viewport);
  57634. }
  57635. scene.resetCachedMaterial();
  57636. };
  57637. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57638. var minimum = 128;
  57639. var x = renderDimension * scale;
  57640. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57641. // Ensure we don't exceed the render dimension (while staying POT)
  57642. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57643. };
  57644. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57645. var _this = this;
  57646. if (!this._texture) {
  57647. return;
  57648. }
  57649. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57650. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57651. });
  57652. };
  57653. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57654. var scene = this.getScene();
  57655. if (!scene) {
  57656. return;
  57657. }
  57658. var engine = scene.getEngine();
  57659. if (!this._texture) {
  57660. return;
  57661. }
  57662. // Bind
  57663. if (this._postProcessManager) {
  57664. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57665. }
  57666. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57667. if (this._texture) {
  57668. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57669. }
  57670. }
  57671. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57672. // Clear
  57673. if (this.onClearObservable.hasObservers()) {
  57674. this.onClearObservable.notifyObservers(engine);
  57675. }
  57676. else {
  57677. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57678. }
  57679. if (!this._doNotChangeAspectRatio) {
  57680. scene.updateTransformMatrix(true);
  57681. }
  57682. // Render
  57683. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57684. if (this._postProcessManager) {
  57685. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57686. }
  57687. else if (useCameraPostProcess) {
  57688. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57689. }
  57690. if (!this._doNotChangeAspectRatio) {
  57691. scene.updateTransformMatrix(true);
  57692. }
  57693. // Dump ?
  57694. if (dumpForDebug) {
  57695. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57696. }
  57697. // Unbind
  57698. if (!this.isCube || faceIndex === 5) {
  57699. if (this.isCube) {
  57700. if (faceIndex === 5) {
  57701. engine.generateMipMapsForCubemap(this._texture);
  57702. }
  57703. }
  57704. this.unbindFrameBuffer(engine, faceIndex);
  57705. }
  57706. else {
  57707. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57708. }
  57709. };
  57710. /**
  57711. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57712. * This allowed control for front to back rendering or reversly depending of the special needs.
  57713. *
  57714. * @param renderingGroupId The rendering group id corresponding to its index
  57715. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57716. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57717. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57718. */
  57719. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57720. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57721. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57722. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57723. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57724. };
  57725. /**
  57726. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57727. *
  57728. * @param renderingGroupId The rendering group id corresponding to its index
  57729. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57730. */
  57731. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57732. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57733. };
  57734. RenderTargetTexture.prototype.clone = function () {
  57735. var textureSize = this.getSize();
  57736. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  57737. // Base texture
  57738. newTexture.hasAlpha = this.hasAlpha;
  57739. newTexture.level = this.level;
  57740. // RenderTarget Texture
  57741. newTexture.coordinatesMode = this.coordinatesMode;
  57742. if (this.renderList) {
  57743. newTexture.renderList = this.renderList.slice(0);
  57744. }
  57745. return newTexture;
  57746. };
  57747. RenderTargetTexture.prototype.serialize = function () {
  57748. if (!this.name) {
  57749. return null;
  57750. }
  57751. var serializationObject = _super.prototype.serialize.call(this);
  57752. serializationObject.renderTargetSize = this.getRenderSize();
  57753. serializationObject.renderList = [];
  57754. if (this.renderList) {
  57755. for (var index = 0; index < this.renderList.length; index++) {
  57756. serializationObject.renderList.push(this.renderList[index].id);
  57757. }
  57758. }
  57759. return serializationObject;
  57760. };
  57761. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57762. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57763. var objBuffer = this.getInternalTexture();
  57764. var scene = this.getScene();
  57765. if (objBuffer && scene) {
  57766. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57767. }
  57768. };
  57769. RenderTargetTexture.prototype.dispose = function () {
  57770. if (this._postProcessManager) {
  57771. this._postProcessManager.dispose();
  57772. this._postProcessManager = null;
  57773. }
  57774. this.clearPostProcesses(true);
  57775. if (this._resizeObserver) {
  57776. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57777. this._resizeObserver = null;
  57778. }
  57779. this.renderList = null;
  57780. // Remove from custom render targets
  57781. var scene = this.getScene();
  57782. if (!scene) {
  57783. return;
  57784. }
  57785. var index = scene.customRenderTargets.indexOf(this);
  57786. if (index >= 0) {
  57787. scene.customRenderTargets.splice(index, 1);
  57788. }
  57789. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57790. var camera = _a[_i];
  57791. index = camera.customRenderTargets.indexOf(this);
  57792. if (index >= 0) {
  57793. camera.customRenderTargets.splice(index, 1);
  57794. }
  57795. }
  57796. _super.prototype.dispose.call(this);
  57797. };
  57798. RenderTargetTexture.prototype._rebuild = function () {
  57799. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57800. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57801. }
  57802. if (this._postProcessManager) {
  57803. this._postProcessManager._rebuild();
  57804. }
  57805. };
  57806. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57807. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57808. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57809. return RenderTargetTexture;
  57810. }(BABYLON.Texture));
  57811. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57812. })(BABYLON || (BABYLON = {}));
  57813. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57814. var BABYLON;
  57815. (function (BABYLON) {
  57816. ;
  57817. var MultiRenderTarget = /** @class */ (function (_super) {
  57818. __extends(MultiRenderTarget, _super);
  57819. function MultiRenderTarget(name, size, count, scene, options) {
  57820. var _this = this;
  57821. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57822. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57823. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57824. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57825. _this._engine = scene.getEngine();
  57826. if (!_this.isSupported) {
  57827. _this.dispose();
  57828. return;
  57829. }
  57830. var types = [];
  57831. var samplingModes = [];
  57832. for (var i = 0; i < count; i++) {
  57833. if (options && options.types && options.types[i] !== undefined) {
  57834. types.push(options.types[i]);
  57835. }
  57836. else {
  57837. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57838. }
  57839. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57840. samplingModes.push(options.samplingModes[i]);
  57841. }
  57842. else {
  57843. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57844. }
  57845. }
  57846. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57847. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57848. _this._size = size;
  57849. _this._multiRenderTargetOptions = {
  57850. samplingModes: samplingModes,
  57851. generateMipMaps: generateMipMaps,
  57852. generateDepthBuffer: generateDepthBuffer,
  57853. generateStencilBuffer: generateStencilBuffer,
  57854. generateDepthTexture: generateDepthTexture,
  57855. types: types,
  57856. textureCount: count
  57857. };
  57858. _this._createInternalTextures();
  57859. _this._createTextures();
  57860. return _this;
  57861. }
  57862. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57863. get: function () {
  57864. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57865. },
  57866. enumerable: true,
  57867. configurable: true
  57868. });
  57869. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57870. get: function () {
  57871. return this._textures;
  57872. },
  57873. enumerable: true,
  57874. configurable: true
  57875. });
  57876. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57877. get: function () {
  57878. return this._textures[this._textures.length - 1];
  57879. },
  57880. enumerable: true,
  57881. configurable: true
  57882. });
  57883. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57884. set: function (wrap) {
  57885. if (this._textures) {
  57886. for (var i = 0; i < this._textures.length; i++) {
  57887. this._textures[i].wrapU = wrap;
  57888. }
  57889. }
  57890. },
  57891. enumerable: true,
  57892. configurable: true
  57893. });
  57894. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57895. set: function (wrap) {
  57896. if (this._textures) {
  57897. for (var i = 0; i < this._textures.length; i++) {
  57898. this._textures[i].wrapV = wrap;
  57899. }
  57900. }
  57901. },
  57902. enumerable: true,
  57903. configurable: true
  57904. });
  57905. MultiRenderTarget.prototype._rebuild = function () {
  57906. this.releaseInternalTextures();
  57907. this._createInternalTextures();
  57908. for (var i = 0; i < this._internalTextures.length; i++) {
  57909. var texture = this._textures[i];
  57910. texture._texture = this._internalTextures[i];
  57911. }
  57912. // Keeps references to frame buffer and stencil/depth buffer
  57913. this._texture = this._internalTextures[0];
  57914. };
  57915. MultiRenderTarget.prototype._createInternalTextures = function () {
  57916. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57917. };
  57918. MultiRenderTarget.prototype._createTextures = function () {
  57919. this._textures = [];
  57920. for (var i = 0; i < this._internalTextures.length; i++) {
  57921. var texture = new BABYLON.Texture(null, this.getScene());
  57922. texture._texture = this._internalTextures[i];
  57923. this._textures.push(texture);
  57924. }
  57925. // Keeps references to frame buffer and stencil/depth buffer
  57926. this._texture = this._internalTextures[0];
  57927. };
  57928. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57929. get: function () {
  57930. return this._samples;
  57931. },
  57932. set: function (value) {
  57933. if (this._samples === value) {
  57934. return;
  57935. }
  57936. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57937. },
  57938. enumerable: true,
  57939. configurable: true
  57940. });
  57941. MultiRenderTarget.prototype.resize = function (size) {
  57942. this.releaseInternalTextures();
  57943. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57944. this._createInternalTextures();
  57945. };
  57946. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57947. var _this = this;
  57948. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57949. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57950. });
  57951. };
  57952. MultiRenderTarget.prototype.dispose = function () {
  57953. this.releaseInternalTextures();
  57954. _super.prototype.dispose.call(this);
  57955. };
  57956. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57957. if (!this._internalTextures) {
  57958. return;
  57959. }
  57960. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57961. if (this._internalTextures[i] !== undefined) {
  57962. this._internalTextures[i].dispose();
  57963. this._internalTextures.splice(i, 1);
  57964. }
  57965. }
  57966. };
  57967. return MultiRenderTarget;
  57968. }(BABYLON.RenderTargetTexture));
  57969. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57970. })(BABYLON || (BABYLON = {}));
  57971. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57972. var BABYLON;
  57973. (function (BABYLON) {
  57974. var MirrorTexture = /** @class */ (function (_super) {
  57975. __extends(MirrorTexture, _super);
  57976. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57977. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57979. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57980. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57981. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57982. _this._transformMatrix = BABYLON.Matrix.Zero();
  57983. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57984. _this._adaptiveBlurKernel = 0;
  57985. _this._blurKernelX = 0;
  57986. _this._blurKernelY = 0;
  57987. _this._blurRatio = 1.0;
  57988. _this.ignoreCameraViewport = true;
  57989. _this.onBeforeRenderObservable.add(function () {
  57990. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57991. _this._savedViewMatrix = scene.getViewMatrix();
  57992. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57993. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57994. scene.clipPlane = _this.mirrorPlane;
  57995. scene.getEngine().cullBackFaces = false;
  57996. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57997. });
  57998. _this.onAfterRenderObservable.add(function () {
  57999. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58000. scene.getEngine().cullBackFaces = true;
  58001. scene._mirroredCameraPosition = null;
  58002. delete scene.clipPlane;
  58003. });
  58004. return _this;
  58005. }
  58006. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58007. get: function () {
  58008. return this._blurRatio;
  58009. },
  58010. set: function (value) {
  58011. if (this._blurRatio === value) {
  58012. return;
  58013. }
  58014. this._blurRatio = value;
  58015. this._preparePostProcesses();
  58016. },
  58017. enumerable: true,
  58018. configurable: true
  58019. });
  58020. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58021. set: function (value) {
  58022. this._adaptiveBlurKernel = value;
  58023. this._autoComputeBlurKernel();
  58024. },
  58025. enumerable: true,
  58026. configurable: true
  58027. });
  58028. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58029. set: function (value) {
  58030. this.blurKernelX = value;
  58031. this.blurKernelY = value;
  58032. },
  58033. enumerable: true,
  58034. configurable: true
  58035. });
  58036. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58037. get: function () {
  58038. return this._blurKernelX;
  58039. },
  58040. set: function (value) {
  58041. if (this._blurKernelX === value) {
  58042. return;
  58043. }
  58044. this._blurKernelX = value;
  58045. this._preparePostProcesses();
  58046. },
  58047. enumerable: true,
  58048. configurable: true
  58049. });
  58050. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58051. get: function () {
  58052. return this._blurKernelY;
  58053. },
  58054. set: function (value) {
  58055. if (this._blurKernelY === value) {
  58056. return;
  58057. }
  58058. this._blurKernelY = value;
  58059. this._preparePostProcesses();
  58060. },
  58061. enumerable: true,
  58062. configurable: true
  58063. });
  58064. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58065. var engine = this.getScene().getEngine();
  58066. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58067. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58068. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58069. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58070. };
  58071. MirrorTexture.prototype._onRatioRescale = function () {
  58072. if (this._sizeRatio) {
  58073. this.resize(this._initialSizeParameter);
  58074. if (!this._adaptiveBlurKernel) {
  58075. this._preparePostProcesses();
  58076. }
  58077. }
  58078. if (this._adaptiveBlurKernel) {
  58079. this._autoComputeBlurKernel();
  58080. }
  58081. };
  58082. MirrorTexture.prototype._preparePostProcesses = function () {
  58083. this.clearPostProcesses(true);
  58084. if (this._blurKernelX && this._blurKernelY) {
  58085. var engine = this.getScene().getEngine();
  58086. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58087. 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);
  58088. this._blurX.autoClear = false;
  58089. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58090. this._blurX.inputTexture = this._texture;
  58091. }
  58092. else {
  58093. this._blurX.alwaysForcePOT = true;
  58094. }
  58095. 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);
  58096. this._blurY.autoClear = false;
  58097. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58098. this.addPostProcess(this._blurX);
  58099. this.addPostProcess(this._blurY);
  58100. }
  58101. else {
  58102. if (this._blurY) {
  58103. this.removePostProcess(this._blurY);
  58104. this._blurY.dispose();
  58105. this._blurY = null;
  58106. }
  58107. if (this._blurX) {
  58108. this.removePostProcess(this._blurX);
  58109. this._blurX.dispose();
  58110. this._blurX = null;
  58111. }
  58112. }
  58113. };
  58114. MirrorTexture.prototype.clone = function () {
  58115. var scene = this.getScene();
  58116. if (!scene) {
  58117. return this;
  58118. }
  58119. var textureSize = this.getSize();
  58120. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58121. // Base texture
  58122. newTexture.hasAlpha = this.hasAlpha;
  58123. newTexture.level = this.level;
  58124. // Mirror Texture
  58125. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58126. if (this.renderList) {
  58127. newTexture.renderList = this.renderList.slice(0);
  58128. }
  58129. return newTexture;
  58130. };
  58131. MirrorTexture.prototype.serialize = function () {
  58132. if (!this.name) {
  58133. return null;
  58134. }
  58135. var serializationObject = _super.prototype.serialize.call(this);
  58136. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58137. return serializationObject;
  58138. };
  58139. return MirrorTexture;
  58140. }(BABYLON.RenderTargetTexture));
  58141. BABYLON.MirrorTexture = MirrorTexture;
  58142. })(BABYLON || (BABYLON = {}));
  58143. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58144. var BABYLON;
  58145. (function (BABYLON) {
  58146. /**
  58147. * Creates a refraction texture used by refraction channel of the standard material.
  58148. * @param name the texture name
  58149. * @param size size of the underlying texture
  58150. * @param scene root scene
  58151. */
  58152. var RefractionTexture = /** @class */ (function (_super) {
  58153. __extends(RefractionTexture, _super);
  58154. function RefractionTexture(name, size, scene, generateMipMaps) {
  58155. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58156. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58157. _this.depth = 2.0;
  58158. _this.onBeforeRenderObservable.add(function () {
  58159. scene.clipPlane = _this.refractionPlane;
  58160. });
  58161. _this.onAfterRenderObservable.add(function () {
  58162. delete scene.clipPlane;
  58163. });
  58164. return _this;
  58165. }
  58166. RefractionTexture.prototype.clone = function () {
  58167. var scene = this.getScene();
  58168. if (!scene) {
  58169. return this;
  58170. }
  58171. var textureSize = this.getSize();
  58172. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58173. // Base texture
  58174. newTexture.hasAlpha = this.hasAlpha;
  58175. newTexture.level = this.level;
  58176. // Refraction Texture
  58177. newTexture.refractionPlane = this.refractionPlane.clone();
  58178. if (this.renderList) {
  58179. newTexture.renderList = this.renderList.slice(0);
  58180. }
  58181. newTexture.depth = this.depth;
  58182. return newTexture;
  58183. };
  58184. RefractionTexture.prototype.serialize = function () {
  58185. if (!this.name) {
  58186. return null;
  58187. }
  58188. var serializationObject = _super.prototype.serialize.call(this);
  58189. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58190. serializationObject.depth = this.depth;
  58191. return serializationObject;
  58192. };
  58193. return RefractionTexture;
  58194. }(BABYLON.RenderTargetTexture));
  58195. BABYLON.RefractionTexture = RefractionTexture;
  58196. })(BABYLON || (BABYLON = {}));
  58197. //# sourceMappingURL=babylon.refractionTexture.js.map
  58198. var BABYLON;
  58199. (function (BABYLON) {
  58200. var DynamicTexture = /** @class */ (function (_super) {
  58201. __extends(DynamicTexture, _super);
  58202. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58203. if (scene === void 0) { scene = null; }
  58204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58205. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58206. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58207. _this.name = name;
  58208. _this._engine = _this.getScene().getEngine();
  58209. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58210. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58211. _this._generateMipMaps = generateMipMaps;
  58212. if (options.getContext) {
  58213. _this._canvas = options;
  58214. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58215. }
  58216. else {
  58217. _this._canvas = document.createElement("canvas");
  58218. if (options.width) {
  58219. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58220. }
  58221. else {
  58222. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58223. }
  58224. }
  58225. var textureSize = _this.getSize();
  58226. _this._canvas.width = textureSize.width;
  58227. _this._canvas.height = textureSize.height;
  58228. _this._context = _this._canvas.getContext("2d");
  58229. return _this;
  58230. }
  58231. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58232. get: function () {
  58233. return true;
  58234. },
  58235. enumerable: true,
  58236. configurable: true
  58237. });
  58238. DynamicTexture.prototype._recreate = function (textureSize) {
  58239. this._canvas.width = textureSize.width;
  58240. this._canvas.height = textureSize.height;
  58241. this.releaseInternalTexture();
  58242. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58243. };
  58244. DynamicTexture.prototype.scale = function (ratio) {
  58245. var textureSize = this.getSize();
  58246. textureSize.width *= ratio;
  58247. textureSize.height *= ratio;
  58248. this._recreate(textureSize);
  58249. };
  58250. DynamicTexture.prototype.scaleTo = function (width, height) {
  58251. var textureSize = this.getSize();
  58252. textureSize.width = width;
  58253. textureSize.height = height;
  58254. this._recreate(textureSize);
  58255. };
  58256. DynamicTexture.prototype.getContext = function () {
  58257. return this._context;
  58258. };
  58259. DynamicTexture.prototype.clear = function () {
  58260. var size = this.getSize();
  58261. this._context.fillRect(0, 0, size.width, size.height);
  58262. };
  58263. DynamicTexture.prototype.update = function (invertY) {
  58264. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58265. };
  58266. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58267. if (update === void 0) { update = true; }
  58268. var size = this.getSize();
  58269. if (clearColor) {
  58270. this._context.fillStyle = clearColor;
  58271. this._context.fillRect(0, 0, size.width, size.height);
  58272. }
  58273. this._context.font = font;
  58274. if (x === null || x === undefined) {
  58275. var textSize = this._context.measureText(text);
  58276. x = (size.width - textSize.width) / 2;
  58277. }
  58278. if (y === null || y === undefined) {
  58279. var fontSize = parseInt((font.replace(/\D/g, '')));
  58280. ;
  58281. y = (size.height / 2) + (fontSize / 3.65);
  58282. }
  58283. this._context.fillStyle = color;
  58284. this._context.fillText(text, x, y);
  58285. if (update) {
  58286. this.update(invertY);
  58287. }
  58288. };
  58289. DynamicTexture.prototype.clone = function () {
  58290. var scene = this.getScene();
  58291. if (!scene) {
  58292. return this;
  58293. }
  58294. var textureSize = this.getSize();
  58295. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58296. // Base texture
  58297. newTexture.hasAlpha = this.hasAlpha;
  58298. newTexture.level = this.level;
  58299. // Dynamic Texture
  58300. newTexture.wrapU = this.wrapU;
  58301. newTexture.wrapV = this.wrapV;
  58302. return newTexture;
  58303. };
  58304. DynamicTexture.prototype._rebuild = function () {
  58305. this.update();
  58306. };
  58307. return DynamicTexture;
  58308. }(BABYLON.Texture));
  58309. BABYLON.DynamicTexture = DynamicTexture;
  58310. })(BABYLON || (BABYLON = {}));
  58311. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58312. var BABYLON;
  58313. (function (BABYLON) {
  58314. var VideoTexture = /** @class */ (function (_super) {
  58315. __extends(VideoTexture, _super);
  58316. /**
  58317. * Creates a video texture.
  58318. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58319. * @param {string | null} name optional name, will detect from video source, if not defined
  58320. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58321. * @param {BABYLON.Scene} scene is obviously the current scene.
  58322. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58323. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58324. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58325. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58326. */
  58327. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58328. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58329. if (invertY === void 0) { invertY = false; }
  58330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58331. if (settings === void 0) { settings = {
  58332. autoPlay: true,
  58333. loop: true,
  58334. autoUpdateTexture: true,
  58335. }; }
  58336. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58337. _this._createInternalTexture = function () {
  58338. if (_this._texture != null) {
  58339. return;
  58340. }
  58341. if (!_this._engine.needPOTTextures ||
  58342. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58343. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58344. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58345. }
  58346. else {
  58347. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58348. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58349. _this._generateMipMaps = false;
  58350. }
  58351. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58352. _this._texture.isReady = true;
  58353. _this._updateInternalTexture();
  58354. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58355. _this.onLoadObservable.notifyObservers(_this);
  58356. }
  58357. };
  58358. _this.reset = function () {
  58359. if (_this._texture == null) {
  58360. return;
  58361. }
  58362. _this._texture.dispose();
  58363. _this._texture = null;
  58364. };
  58365. _this._updateInternalTexture = function (e) {
  58366. if (_this._texture == null || !_this._texture.isReady) {
  58367. return;
  58368. }
  58369. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58370. return;
  58371. }
  58372. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58373. };
  58374. _this._engine = _this.getScene().getEngine();
  58375. _this._generateMipMaps = generateMipMaps;
  58376. _this._samplingMode = samplingMode;
  58377. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58378. _this.name = name || _this._getName(src);
  58379. _this.video = _this._getVideo(src);
  58380. if (settings.autoPlay !== undefined) {
  58381. _this.video.autoplay = settings.autoPlay;
  58382. }
  58383. if (settings.loop !== undefined) {
  58384. _this.video.loop = settings.loop;
  58385. }
  58386. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58387. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58388. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58389. _this.video.addEventListener("emptied", _this.reset);
  58390. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58391. _this._createInternalTexture();
  58392. }
  58393. return _this;
  58394. }
  58395. VideoTexture.prototype._getName = function (src) {
  58396. if (src instanceof HTMLVideoElement) {
  58397. return src.currentSrc;
  58398. }
  58399. if (typeof src === "object") {
  58400. return src.toString();
  58401. }
  58402. return src;
  58403. };
  58404. ;
  58405. VideoTexture.prototype._getVideo = function (src) {
  58406. if (src instanceof HTMLVideoElement) {
  58407. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58408. return src;
  58409. }
  58410. var video = document.createElement("video");
  58411. if (typeof src === "string") {
  58412. BABYLON.Tools.SetCorsBehavior(src, video);
  58413. video.src = src;
  58414. }
  58415. else {
  58416. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58417. src.forEach(function (url) {
  58418. var source = document.createElement("source");
  58419. source.src = url;
  58420. video.appendChild(source);
  58421. });
  58422. }
  58423. return video;
  58424. };
  58425. ;
  58426. /**
  58427. * Internal method to initiate `update`.
  58428. */
  58429. VideoTexture.prototype._rebuild = function () {
  58430. this.update();
  58431. };
  58432. /**
  58433. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58434. */
  58435. VideoTexture.prototype.update = function () {
  58436. if (!this.autoUpdateTexture) {
  58437. // Expecting user to call `updateTexture` manually
  58438. return;
  58439. }
  58440. this.updateTexture(true);
  58441. };
  58442. /**
  58443. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58444. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58445. */
  58446. VideoTexture.prototype.updateTexture = function (isVisible) {
  58447. if (!isVisible) {
  58448. return;
  58449. }
  58450. if (this.video.paused) {
  58451. return;
  58452. }
  58453. this._updateInternalTexture();
  58454. };
  58455. /**
  58456. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58457. * @param url New url.
  58458. */
  58459. VideoTexture.prototype.updateURL = function (url) {
  58460. this.video.src = url;
  58461. };
  58462. VideoTexture.prototype.dispose = function () {
  58463. _super.prototype.dispose.call(this);
  58464. this.video.removeEventListener("canplay", this._createInternalTexture);
  58465. this.video.removeEventListener("paused", this._updateInternalTexture);
  58466. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58467. this.video.removeEventListener("emptied", this.reset);
  58468. this.video.pause();
  58469. };
  58470. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58471. var video = document.createElement("video");
  58472. var constraintsDeviceId;
  58473. if (constraints && constraints.deviceId) {
  58474. constraintsDeviceId = {
  58475. exact: constraints.deviceId,
  58476. };
  58477. }
  58478. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58479. if (navigator.mediaDevices) {
  58480. navigator.mediaDevices.getUserMedia({ video: constraints })
  58481. .then(function (stream) {
  58482. if (video.mozSrcObject !== undefined) {
  58483. // hack for Firefox < 19
  58484. video.mozSrcObject = stream;
  58485. }
  58486. else {
  58487. video.srcObject = stream;
  58488. }
  58489. var onPlaying = function () {
  58490. if (onReady) {
  58491. onReady(new VideoTexture("video", video, scene, true, true));
  58492. }
  58493. video.removeEventListener("playing", onPlaying);
  58494. };
  58495. video.addEventListener("playing", onPlaying);
  58496. video.play();
  58497. })
  58498. .catch(function (err) {
  58499. BABYLON.Tools.Error(err.name);
  58500. });
  58501. }
  58502. else {
  58503. navigator.getUserMedia =
  58504. navigator.getUserMedia ||
  58505. navigator.webkitGetUserMedia ||
  58506. navigator.mozGetUserMedia ||
  58507. navigator.msGetUserMedia;
  58508. if (navigator.getUserMedia) {
  58509. navigator.getUserMedia({
  58510. video: {
  58511. deviceId: constraintsDeviceId,
  58512. width: {
  58513. min: (constraints && constraints.minWidth) || 256,
  58514. max: (constraints && constraints.maxWidth) || 640,
  58515. },
  58516. height: {
  58517. min: (constraints && constraints.minHeight) || 256,
  58518. max: (constraints && constraints.maxHeight) || 480,
  58519. },
  58520. },
  58521. }, function (stream) {
  58522. if (video.mozSrcObject !== undefined) {
  58523. // hack for Firefox < 19
  58524. video.mozSrcObject = stream;
  58525. }
  58526. else {
  58527. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58528. }
  58529. video.play();
  58530. if (onReady) {
  58531. onReady(new VideoTexture("video", video, scene, true, true));
  58532. }
  58533. }, function (e) {
  58534. BABYLON.Tools.Error(e.name);
  58535. });
  58536. }
  58537. }
  58538. };
  58539. return VideoTexture;
  58540. }(BABYLON.Texture));
  58541. BABYLON.VideoTexture = VideoTexture;
  58542. })(BABYLON || (BABYLON = {}));
  58543. //# sourceMappingURL=babylon.videoTexture.js.map
  58544. var BABYLON;
  58545. (function (BABYLON) {
  58546. var RawTexture = /** @class */ (function (_super) {
  58547. __extends(RawTexture, _super);
  58548. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58550. if (invertY === void 0) { invertY = false; }
  58551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58552. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58553. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58554. _this.format = format;
  58555. _this._engine = scene.getEngine();
  58556. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58557. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58558. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58559. return _this;
  58560. }
  58561. RawTexture.prototype.update = function (data) {
  58562. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58563. };
  58564. // Statics
  58565. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58566. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58567. if (invertY === void 0) { invertY = false; }
  58568. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58569. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58570. };
  58571. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58573. if (invertY === void 0) { invertY = false; }
  58574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58576. };
  58577. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58579. if (invertY === void 0) { invertY = false; }
  58580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58581. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58582. };
  58583. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58585. if (invertY === void 0) { invertY = false; }
  58586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58587. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58588. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58589. };
  58590. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58591. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58592. if (invertY === void 0) { invertY = false; }
  58593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58594. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58595. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58596. };
  58597. return RawTexture;
  58598. }(BABYLON.Texture));
  58599. BABYLON.RawTexture = RawTexture;
  58600. })(BABYLON || (BABYLON = {}));
  58601. //# sourceMappingURL=babylon.rawTexture.js.map
  58602. var BABYLON;
  58603. (function (BABYLON) {
  58604. /**
  58605. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58606. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58607. */
  58608. var PostProcess = /** @class */ (function () {
  58609. /**
  58610. * Creates a new instance of @see PostProcess
  58611. * @param name The name of the PostProcess.
  58612. * @param fragmentUrl The url of the fragment shader to be used.
  58613. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58614. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58615. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58616. * @param camera The camera to apply the render pass to.
  58617. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58618. * @param engine The engine which the post process will be applied. (default: current engine)
  58619. * @param reusable If the post process can be reused on the same frame. (default: false)
  58620. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58621. * @param textureType Type of textures used when performing the post process. (default: 0)
  58622. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58623. * @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
  58624. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58625. */
  58626. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58628. if (defines === void 0) { defines = null; }
  58629. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58630. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58631. if (blockCompilation === void 0) { blockCompilation = false; }
  58632. this.name = name;
  58633. /**
  58634. * Width of the texture to apply the post process on
  58635. */
  58636. this.width = -1;
  58637. /**
  58638. * Height of the texture to apply the post process on
  58639. */
  58640. this.height = -1;
  58641. /**
  58642. * If the buffer needs to be cleared before applying the post process. (default: true)
  58643. * Should be set to false if shader will overwrite all previous pixels.
  58644. */
  58645. this.autoClear = true;
  58646. /**
  58647. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58648. */
  58649. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58650. /**
  58651. * Animations to be used for the post processing
  58652. */
  58653. this.animations = new Array();
  58654. /**
  58655. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58656. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58657. */
  58658. this.enablePixelPerfectMode = false;
  58659. /**
  58660. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58661. */
  58662. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58663. /**
  58664. * Force textures to be a power of two (default: false)
  58665. */
  58666. this.alwaysForcePOT = false;
  58667. /**
  58668. * Number of sample textures (default: 1)
  58669. */
  58670. this.samples = 1;
  58671. /**
  58672. * Modify the scale of the post process to be the same as the viewport (default: false)
  58673. */
  58674. this.adaptScaleToCurrentViewport = false;
  58675. this._reusable = false;
  58676. /**
  58677. * Smart array of input and output textures for the post process.
  58678. */
  58679. this._textures = new BABYLON.SmartArray(2);
  58680. /**
  58681. * The index in _textures that corresponds to the output texture.
  58682. */
  58683. this._currentRenderTextureInd = 0;
  58684. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58685. this._texelSize = BABYLON.Vector2.Zero();
  58686. // Events
  58687. /**
  58688. * An event triggered when the postprocess is activated.
  58689. * @type {BABYLON.Observable}
  58690. */
  58691. this.onActivateObservable = new BABYLON.Observable();
  58692. /**
  58693. * An event triggered when the postprocess changes its size.
  58694. * @type {BABYLON.Observable}
  58695. */
  58696. this.onSizeChangedObservable = new BABYLON.Observable();
  58697. /**
  58698. * An event triggered when the postprocess applies its effect.
  58699. * @type {BABYLON.Observable}
  58700. */
  58701. this.onApplyObservable = new BABYLON.Observable();
  58702. /**
  58703. * An event triggered before rendering the postprocess
  58704. * @type {BABYLON.Observable}
  58705. */
  58706. this.onBeforeRenderObservable = new BABYLON.Observable();
  58707. /**
  58708. * An event triggered after rendering the postprocess
  58709. * @type {BABYLON.Observable}
  58710. */
  58711. this.onAfterRenderObservable = new BABYLON.Observable();
  58712. if (camera != null) {
  58713. this._camera = camera;
  58714. this._scene = camera.getScene();
  58715. camera.attachPostProcess(this);
  58716. this._engine = this._scene.getEngine();
  58717. this._scene.postProcesses.push(this);
  58718. }
  58719. else if (engine) {
  58720. this._engine = engine;
  58721. this._engine.postProcesses.push(this);
  58722. }
  58723. this._options = options;
  58724. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58725. this._reusable = reusable || false;
  58726. this._textureType = textureType;
  58727. this._samplers = samplers || [];
  58728. this._samplers.push("textureSampler");
  58729. this._fragmentUrl = fragmentUrl;
  58730. this._vertexUrl = vertexUrl;
  58731. this._parameters = parameters || [];
  58732. this._parameters.push("scale");
  58733. this._indexParameters = indexParameters;
  58734. if (!blockCompilation) {
  58735. this.updateEffect(defines);
  58736. }
  58737. }
  58738. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58739. /**
  58740. * A function that is added to the onActivateObservable
  58741. */
  58742. set: function (callback) {
  58743. if (this._onActivateObserver) {
  58744. this.onActivateObservable.remove(this._onActivateObserver);
  58745. }
  58746. if (callback) {
  58747. this._onActivateObserver = this.onActivateObservable.add(callback);
  58748. }
  58749. },
  58750. enumerable: true,
  58751. configurable: true
  58752. });
  58753. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58754. /**
  58755. * A function that is added to the onSizeChangedObservable
  58756. */
  58757. set: function (callback) {
  58758. if (this._onSizeChangedObserver) {
  58759. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58760. }
  58761. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58762. },
  58763. enumerable: true,
  58764. configurable: true
  58765. });
  58766. Object.defineProperty(PostProcess.prototype, "onApply", {
  58767. /**
  58768. * A function that is added to the onApplyObservable
  58769. */
  58770. set: function (callback) {
  58771. if (this._onApplyObserver) {
  58772. this.onApplyObservable.remove(this._onApplyObserver);
  58773. }
  58774. this._onApplyObserver = this.onApplyObservable.add(callback);
  58775. },
  58776. enumerable: true,
  58777. configurable: true
  58778. });
  58779. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58780. /**
  58781. * A function that is added to the onBeforeRenderObservable
  58782. */
  58783. set: function (callback) {
  58784. if (this._onBeforeRenderObserver) {
  58785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58786. }
  58787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58788. },
  58789. enumerable: true,
  58790. configurable: true
  58791. });
  58792. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58793. /**
  58794. * A function that is added to the onAfterRenderObservable
  58795. */
  58796. set: function (callback) {
  58797. if (this._onAfterRenderObserver) {
  58798. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58799. }
  58800. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58801. },
  58802. enumerable: true,
  58803. configurable: true
  58804. });
  58805. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58806. /**
  58807. * 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
  58808. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58809. */
  58810. get: function () {
  58811. return this._textures.data[this._currentRenderTextureInd];
  58812. },
  58813. set: function (value) {
  58814. this._forcedOutputTexture = value;
  58815. },
  58816. enumerable: true,
  58817. configurable: true
  58818. });
  58819. /**
  58820. * Gets the camera which post process is applied to.
  58821. * @returns The camera the post process is applied to.
  58822. */
  58823. PostProcess.prototype.getCamera = function () {
  58824. return this._camera;
  58825. };
  58826. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58827. /**
  58828. * Gets the texel size of the postprocess.
  58829. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58830. */
  58831. get: function () {
  58832. if (this._shareOutputWithPostProcess) {
  58833. return this._shareOutputWithPostProcess.texelSize;
  58834. }
  58835. if (this._forcedOutputTexture) {
  58836. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58837. }
  58838. return this._texelSize;
  58839. },
  58840. enumerable: true,
  58841. configurable: true
  58842. });
  58843. /**
  58844. * Gets the engine which this post process belongs to.
  58845. * @returns The engine the post process was enabled with.
  58846. */
  58847. PostProcess.prototype.getEngine = function () {
  58848. return this._engine;
  58849. };
  58850. /**
  58851. * The effect that is created when initializing the post process.
  58852. * @returns The created effect corrisponding the the postprocess.
  58853. */
  58854. PostProcess.prototype.getEffect = function () {
  58855. return this._effect;
  58856. };
  58857. /**
  58858. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58859. * @param postProcess The post process to share the output with.
  58860. * @returns This post process.
  58861. */
  58862. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58863. this._disposeTextures();
  58864. this._shareOutputWithPostProcess = postProcess;
  58865. return this;
  58866. };
  58867. /**
  58868. * Updates the effect with the current post process compile time values and recompiles the shader.
  58869. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58870. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58871. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58872. * @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
  58873. * @param onCompiled Called when the shader has been compiled.
  58874. * @param onError Called if there is an error when compiling a shader.
  58875. */
  58876. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58877. if (defines === void 0) { defines = null; }
  58878. if (uniforms === void 0) { uniforms = null; }
  58879. if (samplers === void 0) { samplers = null; }
  58880. 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);
  58881. };
  58882. /**
  58883. * The post process is reusable if it can be used multiple times within one frame.
  58884. * @returns If the post process is reusable
  58885. */
  58886. PostProcess.prototype.isReusable = function () {
  58887. return this._reusable;
  58888. };
  58889. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58890. PostProcess.prototype.markTextureDirty = function () {
  58891. this.width = -1;
  58892. };
  58893. /**
  58894. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58895. * 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.
  58896. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58897. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58898. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58899. */
  58900. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58901. var _this = this;
  58902. if (sourceTexture === void 0) { sourceTexture = null; }
  58903. camera = camera || this._camera;
  58904. var scene = camera.getScene();
  58905. var engine = scene.getEngine();
  58906. var maxSize = engine.getCaps().maxTextureSize;
  58907. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58908. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58909. // 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
  58910. var webVRCamera = camera.parent;
  58911. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  58912. requiredWidth /= 2;
  58913. }
  58914. var desiredWidth = (this._options.width || requiredWidth);
  58915. var desiredHeight = this._options.height || requiredHeight;
  58916. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58917. if (this.adaptScaleToCurrentViewport) {
  58918. var currentViewport = engine.currentViewport;
  58919. if (currentViewport) {
  58920. desiredWidth *= currentViewport.width;
  58921. desiredHeight *= currentViewport.height;
  58922. }
  58923. }
  58924. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58925. if (!this._options.width) {
  58926. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58927. }
  58928. if (!this._options.height) {
  58929. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58930. }
  58931. }
  58932. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58933. if (this._textures.length > 0) {
  58934. for (var i = 0; i < this._textures.length; i++) {
  58935. this._engine._releaseTexture(this._textures.data[i]);
  58936. }
  58937. this._textures.reset();
  58938. }
  58939. this.width = desiredWidth;
  58940. this.height = desiredHeight;
  58941. var textureSize = { width: this.width, height: this.height };
  58942. var textureOptions = {
  58943. generateMipMaps: false,
  58944. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58945. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58946. samplingMode: this.renderTargetSamplingMode,
  58947. type: this._textureType
  58948. };
  58949. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58950. if (this._reusable) {
  58951. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58952. }
  58953. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58954. this.onSizeChangedObservable.notifyObservers(this);
  58955. }
  58956. this._textures.forEach(function (texture) {
  58957. if (texture.samples !== _this.samples) {
  58958. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58959. }
  58960. });
  58961. }
  58962. var target;
  58963. if (this._shareOutputWithPostProcess) {
  58964. target = this._shareOutputWithPostProcess.inputTexture;
  58965. }
  58966. else if (this._forcedOutputTexture) {
  58967. target = this._forcedOutputTexture;
  58968. this.width = this._forcedOutputTexture.width;
  58969. this.height = this._forcedOutputTexture.height;
  58970. }
  58971. else {
  58972. target = this.inputTexture;
  58973. }
  58974. // Bind the input of this post process to be used as the output of the previous post process.
  58975. if (this.enablePixelPerfectMode) {
  58976. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58977. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58978. }
  58979. else {
  58980. this._scaleRatio.copyFromFloats(1, 1);
  58981. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58982. }
  58983. this.onActivateObservable.notifyObservers(camera);
  58984. // Clear
  58985. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58986. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58987. }
  58988. if (this._reusable) {
  58989. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58990. }
  58991. };
  58992. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58993. /**
  58994. * If the post process is supported.
  58995. */
  58996. get: function () {
  58997. return this._effect.isSupported;
  58998. },
  58999. enumerable: true,
  59000. configurable: true
  59001. });
  59002. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59003. /**
  59004. * The aspect ratio of the output texture.
  59005. */
  59006. get: function () {
  59007. if (this._shareOutputWithPostProcess) {
  59008. return this._shareOutputWithPostProcess.aspectRatio;
  59009. }
  59010. if (this._forcedOutputTexture) {
  59011. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59012. }
  59013. return this.width / this.height;
  59014. },
  59015. enumerable: true,
  59016. configurable: true
  59017. });
  59018. /**
  59019. * Get a value indicating if the post-process is ready to be used
  59020. * @returns true if the post-process is ready (shader is compiled)
  59021. */
  59022. PostProcess.prototype.isReady = function () {
  59023. return this._effect && this._effect.isReady();
  59024. };
  59025. /**
  59026. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59027. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59028. */
  59029. PostProcess.prototype.apply = function () {
  59030. // Check
  59031. if (!this._effect || !this._effect.isReady())
  59032. return null;
  59033. // States
  59034. this._engine.enableEffect(this._effect);
  59035. this._engine.setState(false);
  59036. this._engine.setDepthBuffer(false);
  59037. this._engine.setDepthWrite(false);
  59038. // Alpha
  59039. this._engine.setAlphaMode(this.alphaMode);
  59040. if (this.alphaConstants) {
  59041. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59042. }
  59043. // Bind the output texture of the preivous post process as the input to this post process.
  59044. var source;
  59045. if (this._shareOutputWithPostProcess) {
  59046. source = this._shareOutputWithPostProcess.inputTexture;
  59047. }
  59048. else if (this._forcedOutputTexture) {
  59049. source = this._forcedOutputTexture;
  59050. }
  59051. else {
  59052. source = this.inputTexture;
  59053. }
  59054. this._effect._bindTexture("textureSampler", source);
  59055. // Parameters
  59056. this._effect.setVector2("scale", this._scaleRatio);
  59057. this.onApplyObservable.notifyObservers(this._effect);
  59058. return this._effect;
  59059. };
  59060. PostProcess.prototype._disposeTextures = function () {
  59061. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59062. return;
  59063. }
  59064. if (this._textures.length > 0) {
  59065. for (var i = 0; i < this._textures.length; i++) {
  59066. this._engine._releaseTexture(this._textures.data[i]);
  59067. }
  59068. }
  59069. this._textures.dispose();
  59070. };
  59071. /**
  59072. * Disposes the post process.
  59073. * @param camera The camera to dispose the post process on.
  59074. */
  59075. PostProcess.prototype.dispose = function (camera) {
  59076. camera = camera || this._camera;
  59077. this._disposeTextures();
  59078. if (this._scene) {
  59079. var index_1 = this._scene.postProcesses.indexOf(this);
  59080. if (index_1 !== -1) {
  59081. this._scene.postProcesses.splice(index_1, 1);
  59082. }
  59083. }
  59084. else {
  59085. var index_2 = this._engine.postProcesses.indexOf(this);
  59086. if (index_2 !== -1) {
  59087. this._engine.postProcesses.splice(index_2, 1);
  59088. }
  59089. }
  59090. if (!camera) {
  59091. return;
  59092. }
  59093. camera.detachPostProcess(this);
  59094. var index = camera._postProcesses.indexOf(this);
  59095. if (index === 0 && camera._postProcesses.length > 0) {
  59096. this._camera._postProcesses[0].markTextureDirty();
  59097. }
  59098. this.onActivateObservable.clear();
  59099. this.onAfterRenderObservable.clear();
  59100. this.onApplyObservable.clear();
  59101. this.onBeforeRenderObservable.clear();
  59102. this.onSizeChangedObservable.clear();
  59103. };
  59104. return PostProcess;
  59105. }());
  59106. BABYLON.PostProcess = PostProcess;
  59107. })(BABYLON || (BABYLON = {}));
  59108. //# sourceMappingURL=babylon.postProcess.js.map
  59109. var BABYLON;
  59110. (function (BABYLON) {
  59111. var PassPostProcess = /** @class */ (function (_super) {
  59112. __extends(PassPostProcess, _super);
  59113. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59114. if (camera === void 0) { camera = null; }
  59115. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59116. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59117. }
  59118. return PassPostProcess;
  59119. }(BABYLON.PostProcess));
  59120. BABYLON.PassPostProcess = PassPostProcess;
  59121. })(BABYLON || (BABYLON = {}));
  59122. //# sourceMappingURL=babylon.passPostProcess.js.map
  59123. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59124. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59125. s = arguments[i];
  59126. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59127. t[p] = s[p];
  59128. }
  59129. return t;
  59130. };
  59131. var BABYLON;
  59132. (function (BABYLON) {
  59133. /**
  59134. * Default implementation of @see IShadowGenerator.
  59135. * This is the main object responsible of generating shadows in the framework.
  59136. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59137. */
  59138. var ShadowGenerator = /** @class */ (function () {
  59139. /**
  59140. * Creates a ShadowGenerator object.
  59141. * A ShadowGenerator is the required tool to use the shadows.
  59142. * Each light casting shadows needs to use its own ShadowGenerator.
  59143. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59144. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59145. * @param light The light object generating the shadows.
  59146. * @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.
  59147. */
  59148. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59149. this._bias = 0.00005;
  59150. this._blurBoxOffset = 1;
  59151. this._blurScale = 2;
  59152. this._blurKernel = 1;
  59153. this._useKernelBlur = false;
  59154. this._filter = ShadowGenerator.FILTER_NONE;
  59155. this._darkness = 0;
  59156. this._transparencyShadow = false;
  59157. /**
  59158. * Controls the extent to which the shadows fade out at the edge of the frustum
  59159. * Used only by directionals and spots
  59160. */
  59161. this.frustumEdgeFalloff = 0;
  59162. /**
  59163. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59164. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59165. * It might on the other hand introduce peter panning.
  59166. */
  59167. this.forceBackFacesOnly = false;
  59168. this._lightDirection = BABYLON.Vector3.Zero();
  59169. this._viewMatrix = BABYLON.Matrix.Zero();
  59170. this._projectionMatrix = BABYLON.Matrix.Zero();
  59171. this._transformMatrix = BABYLON.Matrix.Zero();
  59172. this._currentFaceIndex = 0;
  59173. this._currentFaceIndexCache = 0;
  59174. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59175. this._mapSize = mapSize;
  59176. this._light = light;
  59177. this._scene = light.getScene();
  59178. light._shadowGenerator = this;
  59179. // Texture type fallback from float to int if not supported.
  59180. var caps = this._scene.getEngine().getCaps();
  59181. if (!useFullFloatFirst) {
  59182. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59183. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59184. }
  59185. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59186. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59187. }
  59188. else {
  59189. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59190. }
  59191. }
  59192. else {
  59193. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59194. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59195. }
  59196. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59197. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59198. }
  59199. else {
  59200. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59201. }
  59202. }
  59203. this._initializeGenerator();
  59204. }
  59205. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59206. /**
  59207. * Shadow generator mode None: no filtering applied.
  59208. */
  59209. get: function () {
  59210. return ShadowGenerator._FILTER_NONE;
  59211. },
  59212. enumerable: true,
  59213. configurable: true
  59214. });
  59215. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59216. /**
  59217. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59218. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59219. */
  59220. get: function () {
  59221. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59222. },
  59223. enumerable: true,
  59224. configurable: true
  59225. });
  59226. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59227. /**
  59228. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59229. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59230. */
  59231. get: function () {
  59232. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59233. },
  59234. enumerable: true,
  59235. configurable: true
  59236. });
  59237. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59238. /**
  59239. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59240. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59241. */
  59242. get: function () {
  59243. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59244. },
  59245. enumerable: true,
  59246. configurable: true
  59247. });
  59248. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59249. /**
  59250. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59251. * edge artifacts on steep falloff.
  59252. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59253. */
  59254. get: function () {
  59255. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59256. },
  59257. enumerable: true,
  59258. configurable: true
  59259. });
  59260. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59261. /**
  59262. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59263. * edge artifacts on steep falloff.
  59264. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59265. */
  59266. get: function () {
  59267. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59273. /**
  59274. * Gets the bias: offset applied on the depth preventing acnea.
  59275. */
  59276. get: function () {
  59277. return this._bias;
  59278. },
  59279. /**
  59280. * Sets the bias: offset applied on the depth preventing acnea.
  59281. */
  59282. set: function (bias) {
  59283. this._bias = bias;
  59284. },
  59285. enumerable: true,
  59286. configurable: true
  59287. });
  59288. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59289. /**
  59290. * Gets the blur box offset: offset applied during the blur pass.
  59291. * Only usefull if useKernelBlur = false
  59292. */
  59293. get: function () {
  59294. return this._blurBoxOffset;
  59295. },
  59296. /**
  59297. * Sets the blur box offset: offset applied during the blur pass.
  59298. * Only usefull if useKernelBlur = false
  59299. */
  59300. set: function (value) {
  59301. if (this._blurBoxOffset === value) {
  59302. return;
  59303. }
  59304. this._blurBoxOffset = value;
  59305. this._disposeBlurPostProcesses();
  59306. },
  59307. enumerable: true,
  59308. configurable: true
  59309. });
  59310. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59311. /**
  59312. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59313. * 2 means half of the size.
  59314. */
  59315. get: function () {
  59316. return this._blurScale;
  59317. },
  59318. /**
  59319. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59320. * 2 means half of the size.
  59321. */
  59322. set: function (value) {
  59323. if (this._blurScale === value) {
  59324. return;
  59325. }
  59326. this._blurScale = value;
  59327. this._disposeBlurPostProcesses();
  59328. },
  59329. enumerable: true,
  59330. configurable: true
  59331. });
  59332. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59333. /**
  59334. * Gets the blur kernel: kernel size of the blur pass.
  59335. * Only usefull if useKernelBlur = true
  59336. */
  59337. get: function () {
  59338. return this._blurKernel;
  59339. },
  59340. /**
  59341. * Sets the blur kernel: kernel size of the blur pass.
  59342. * Only usefull if useKernelBlur = true
  59343. */
  59344. set: function (value) {
  59345. if (this._blurKernel === value) {
  59346. return;
  59347. }
  59348. this._blurKernel = value;
  59349. this._disposeBlurPostProcesses();
  59350. },
  59351. enumerable: true,
  59352. configurable: true
  59353. });
  59354. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59355. /**
  59356. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59357. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59358. */
  59359. get: function () {
  59360. return this._useKernelBlur;
  59361. },
  59362. /**
  59363. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59364. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59365. */
  59366. set: function (value) {
  59367. if (this._useKernelBlur === value) {
  59368. return;
  59369. }
  59370. this._useKernelBlur = value;
  59371. this._disposeBlurPostProcesses();
  59372. },
  59373. enumerable: true,
  59374. configurable: true
  59375. });
  59376. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59377. /**
  59378. * Gets the depth scale used in ESM mode.
  59379. */
  59380. get: function () {
  59381. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59382. },
  59383. /**
  59384. * Sets the depth scale used in ESM mode.
  59385. * This can override the scale stored on the light.
  59386. */
  59387. set: function (value) {
  59388. this._depthScale = value;
  59389. },
  59390. enumerable: true,
  59391. configurable: true
  59392. });
  59393. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59394. /**
  59395. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59396. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59397. */
  59398. get: function () {
  59399. return this._filter;
  59400. },
  59401. /**
  59402. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59403. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59404. */
  59405. set: function (value) {
  59406. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59407. if (this._light.needCube()) {
  59408. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59409. this.useExponentialShadowMap = true;
  59410. return;
  59411. }
  59412. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59413. this.useCloseExponentialShadowMap = true;
  59414. return;
  59415. }
  59416. }
  59417. if (this._filter === value) {
  59418. return;
  59419. }
  59420. this._filter = value;
  59421. this._disposeBlurPostProcesses();
  59422. this._applyFilterValues();
  59423. this._light._markMeshesAsLightDirty();
  59424. },
  59425. enumerable: true,
  59426. configurable: true
  59427. });
  59428. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59429. /**
  59430. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59431. */
  59432. get: function () {
  59433. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59434. },
  59435. /**
  59436. * Sets the current filter to Poisson Sampling aka PCF.
  59437. */
  59438. set: function (value) {
  59439. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59440. return;
  59441. }
  59442. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59443. },
  59444. enumerable: true,
  59445. configurable: true
  59446. });
  59447. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59448. /**
  59449. * Gets if the current filter is set to VSM.
  59450. * DEPRECATED. Should use useExponentialShadowMap instead.
  59451. */
  59452. get: function () {
  59453. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59454. return this.useExponentialShadowMap;
  59455. },
  59456. /**
  59457. * Sets the current filter is to VSM.
  59458. * DEPRECATED. Should use useExponentialShadowMap instead.
  59459. */
  59460. set: function (value) {
  59461. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59462. this.useExponentialShadowMap = value;
  59463. },
  59464. enumerable: true,
  59465. configurable: true
  59466. });
  59467. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59468. /**
  59469. * Gets if the current filter is set to blurred VSM.
  59470. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59471. */
  59472. get: function () {
  59473. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59474. return this.useBlurExponentialShadowMap;
  59475. },
  59476. /**
  59477. * Sets the current filter is to blurred VSM.
  59478. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59479. */
  59480. set: function (value) {
  59481. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59482. this.useBlurExponentialShadowMap = value;
  59483. },
  59484. enumerable: true,
  59485. configurable: true
  59486. });
  59487. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59488. /**
  59489. * Gets if the current filter is set to ESM.
  59490. */
  59491. get: function () {
  59492. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59493. },
  59494. /**
  59495. * Sets the current filter is to ESM.
  59496. */
  59497. set: function (value) {
  59498. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59499. return;
  59500. }
  59501. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59502. },
  59503. enumerable: true,
  59504. configurable: true
  59505. });
  59506. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59507. /**
  59508. * Gets if the current filter is set to filtered ESM.
  59509. */
  59510. get: function () {
  59511. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59512. },
  59513. /**
  59514. * Gets if the current filter is set to filtered ESM.
  59515. */
  59516. set: function (value) {
  59517. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59518. return;
  59519. }
  59520. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59521. },
  59522. enumerable: true,
  59523. configurable: true
  59524. });
  59525. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59526. /**
  59527. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59528. * exponential to prevent steep falloff artifacts).
  59529. */
  59530. get: function () {
  59531. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59532. },
  59533. /**
  59534. * Sets the current filter to "close ESM" (using the inverse of the
  59535. * exponential to prevent steep falloff artifacts).
  59536. */
  59537. set: function (value) {
  59538. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59539. return;
  59540. }
  59541. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59542. },
  59543. enumerable: true,
  59544. configurable: true
  59545. });
  59546. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59547. /**
  59548. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59549. * exponential to prevent steep falloff artifacts).
  59550. */
  59551. get: function () {
  59552. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59553. },
  59554. /**
  59555. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59556. * exponential to prevent steep falloff artifacts).
  59557. */
  59558. set: function (value) {
  59559. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59560. return;
  59561. }
  59562. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59563. },
  59564. enumerable: true,
  59565. configurable: true
  59566. });
  59567. /**
  59568. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59569. * 0 means strongest and 1 would means no shadow.
  59570. * @returns the darkness.
  59571. */
  59572. ShadowGenerator.prototype.getDarkness = function () {
  59573. return this._darkness;
  59574. };
  59575. /**
  59576. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59577. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59578. * @returns the shadow generator allowing fluent coding.
  59579. */
  59580. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59581. if (darkness >= 1.0)
  59582. this._darkness = 1.0;
  59583. else if (darkness <= 0.0)
  59584. this._darkness = 0.0;
  59585. else
  59586. this._darkness = darkness;
  59587. return this;
  59588. };
  59589. /**
  59590. * Sets the ability to have transparent shadow (boolean).
  59591. * @param transparent True if transparent else False
  59592. * @returns the shadow generator allowing fluent coding
  59593. */
  59594. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59595. this._transparencyShadow = transparent;
  59596. return this;
  59597. };
  59598. /**
  59599. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59600. * @returns The render target texture if present otherwise, null
  59601. */
  59602. ShadowGenerator.prototype.getShadowMap = function () {
  59603. return this._shadowMap;
  59604. };
  59605. /**
  59606. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59607. * @returns The render target texture if the shadow map is present otherwise, null
  59608. */
  59609. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59610. if (this._shadowMap2) {
  59611. return this._shadowMap2;
  59612. }
  59613. return this._shadowMap;
  59614. };
  59615. /**
  59616. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59617. * @param mesh Mesh to add
  59618. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59619. * @returns the Shadow Generator itself
  59620. */
  59621. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59622. if (includeDescendants === void 0) { includeDescendants = true; }
  59623. if (!this._shadowMap) {
  59624. return this;
  59625. }
  59626. if (!this._shadowMap.renderList) {
  59627. this._shadowMap.renderList = [];
  59628. }
  59629. this._shadowMap.renderList.push(mesh);
  59630. if (includeDescendants) {
  59631. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59632. }
  59633. return this;
  59634. var _a;
  59635. };
  59636. /**
  59637. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59638. * @param mesh Mesh to remove
  59639. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59640. * @returns the Shadow Generator itself
  59641. */
  59642. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59643. if (includeDescendants === void 0) { includeDescendants = true; }
  59644. if (!this._shadowMap || !this._shadowMap.renderList) {
  59645. return this;
  59646. }
  59647. var index = this._shadowMap.renderList.indexOf(mesh);
  59648. if (index !== -1) {
  59649. this._shadowMap.renderList.splice(index, 1);
  59650. }
  59651. if (includeDescendants) {
  59652. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59653. var child = _a[_i];
  59654. this.removeShadowCaster(child);
  59655. }
  59656. }
  59657. return this;
  59658. };
  59659. /**
  59660. * Returns the associated light object.
  59661. * @returns the light generating the shadow
  59662. */
  59663. ShadowGenerator.prototype.getLight = function () {
  59664. return this._light;
  59665. };
  59666. ShadowGenerator.prototype._initializeGenerator = function () {
  59667. this._light._markMeshesAsLightDirty();
  59668. this._initializeShadowMap();
  59669. };
  59670. ShadowGenerator.prototype._initializeShadowMap = function () {
  59671. var _this = this;
  59672. // Render target
  59673. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59674. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59675. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59676. this._shadowMap.anisotropicFilteringLevel = 1;
  59677. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59678. this._shadowMap.renderParticles = false;
  59679. this._shadowMap.ignoreCameraViewport = true;
  59680. // Record Face Index before render.
  59681. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59682. _this._currentFaceIndex = faceIndex;
  59683. });
  59684. // Custom render function.
  59685. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59686. // Blur if required afer render.
  59687. this._shadowMap.onAfterUnbindObservable.add(function () {
  59688. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59689. return;
  59690. }
  59691. var shadowMap = _this.getShadowMapForRendering();
  59692. if (shadowMap) {
  59693. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59694. }
  59695. });
  59696. // Clear according to the chosen filter.
  59697. this._shadowMap.onClearObservable.add(function (engine) {
  59698. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59699. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59700. }
  59701. else {
  59702. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59703. }
  59704. });
  59705. };
  59706. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59707. var _this = this;
  59708. var engine = this._scene.getEngine();
  59709. var targetSize = this._mapSize / this.blurScale;
  59710. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59711. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59712. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59713. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59714. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59715. }
  59716. if (this.useKernelBlur) {
  59717. 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);
  59718. this._kernelBlurXPostprocess.width = targetSize;
  59719. this._kernelBlurXPostprocess.height = targetSize;
  59720. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59721. effect.setTexture("textureSampler", _this._shadowMap);
  59722. });
  59723. 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);
  59724. this._kernelBlurXPostprocess.autoClear = false;
  59725. this._kernelBlurYPostprocess.autoClear = false;
  59726. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59727. this._kernelBlurXPostprocess.packedFloat = true;
  59728. this._kernelBlurYPostprocess.packedFloat = true;
  59729. }
  59730. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59731. }
  59732. else {
  59733. 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);
  59734. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59735. effect.setFloat2("screenSize", targetSize, targetSize);
  59736. effect.setTexture("textureSampler", _this._shadowMap);
  59737. });
  59738. this._boxBlurPostprocess.autoClear = false;
  59739. this._blurPostProcesses = [this._boxBlurPostprocess];
  59740. }
  59741. };
  59742. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59743. var index;
  59744. var engine = this._scene.getEngine();
  59745. if (depthOnlySubMeshes.length) {
  59746. engine.setColorWrite(false);
  59747. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59748. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59749. }
  59750. engine.setColorWrite(true);
  59751. }
  59752. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59753. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59754. }
  59755. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59756. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59757. }
  59758. if (this._transparencyShadow) {
  59759. for (index = 0; index < transparentSubMeshes.length; index++) {
  59760. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59761. }
  59762. }
  59763. };
  59764. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59765. var _this = this;
  59766. var mesh = subMesh.getRenderingMesh();
  59767. var scene = this._scene;
  59768. var engine = scene.getEngine();
  59769. var material = subMesh.getMaterial();
  59770. if (!material) {
  59771. return;
  59772. }
  59773. // Culling
  59774. engine.setState(material.backFaceCulling);
  59775. // Managing instances
  59776. var batch = mesh._getInstancesRenderList(subMesh._id);
  59777. if (batch.mustReturn) {
  59778. return;
  59779. }
  59780. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59781. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59782. engine.enableEffect(this._effect);
  59783. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59784. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59785. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59786. this._effect.setVector3("lightPosition", this.getLight().position);
  59787. if (scene.activeCamera) {
  59788. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59789. }
  59790. // Alpha test
  59791. if (material && material.needAlphaTesting()) {
  59792. var alphaTexture = material.getAlphaTestTexture();
  59793. if (alphaTexture) {
  59794. this._effect.setTexture("diffuseSampler", alphaTexture);
  59795. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59796. }
  59797. }
  59798. // Bones
  59799. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59800. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59801. }
  59802. if (this.forceBackFacesOnly) {
  59803. engine.setState(true, 0, false, true);
  59804. }
  59805. // Draw
  59806. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59807. if (this.forceBackFacesOnly) {
  59808. engine.setState(true, 0, false, false);
  59809. }
  59810. }
  59811. else {
  59812. // Need to reset refresh rate of the shadowMap
  59813. if (this._shadowMap) {
  59814. this._shadowMap.resetRefreshCounter();
  59815. }
  59816. }
  59817. };
  59818. ShadowGenerator.prototype._applyFilterValues = function () {
  59819. if (!this._shadowMap) {
  59820. return;
  59821. }
  59822. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59823. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59824. }
  59825. else {
  59826. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59827. }
  59828. };
  59829. /**
  59830. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59831. * @param onCompiled Callback triggered at the and of the effects compilation
  59832. * @param options Sets of optional options forcing the compilation with different modes
  59833. */
  59834. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59835. var _this = this;
  59836. var localOptions = __assign({ useInstances: false }, options);
  59837. var shadowMap = this.getShadowMap();
  59838. if (!shadowMap) {
  59839. if (onCompiled) {
  59840. onCompiled(this);
  59841. }
  59842. return;
  59843. }
  59844. var renderList = shadowMap.renderList;
  59845. if (!renderList) {
  59846. if (onCompiled) {
  59847. onCompiled(this);
  59848. }
  59849. return;
  59850. }
  59851. var subMeshes = new Array();
  59852. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59853. var mesh = renderList_1[_i];
  59854. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59855. }
  59856. if (subMeshes.length === 0) {
  59857. if (onCompiled) {
  59858. onCompiled(this);
  59859. }
  59860. return;
  59861. }
  59862. var currentIndex = 0;
  59863. var checkReady = function () {
  59864. if (!_this._scene || !_this._scene.getEngine()) {
  59865. return;
  59866. }
  59867. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59868. currentIndex++;
  59869. if (currentIndex >= subMeshes.length) {
  59870. if (onCompiled) {
  59871. onCompiled(_this);
  59872. }
  59873. return;
  59874. }
  59875. }
  59876. setTimeout(checkReady, 16);
  59877. };
  59878. checkReady();
  59879. };
  59880. /**
  59881. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59882. * @param options Sets of optional options forcing the compilation with different modes
  59883. * @returns A promise that resolves when the compilation completes
  59884. */
  59885. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59886. var _this = this;
  59887. return new Promise(function (resolve) {
  59888. _this.forceCompilation(function () {
  59889. resolve();
  59890. }, options);
  59891. });
  59892. };
  59893. /**
  59894. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59895. * @param subMesh The submesh we want to render in the shadow map
  59896. * @param useInstances Defines wether will draw in the map using instances
  59897. * @returns true if ready otherwise, false
  59898. */
  59899. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59900. var defines = [];
  59901. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59902. defines.push("#define FLOAT");
  59903. }
  59904. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59905. defines.push("#define ESM");
  59906. }
  59907. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59908. var mesh = subMesh.getMesh();
  59909. var material = subMesh.getMaterial();
  59910. // Alpha test
  59911. if (material && material.needAlphaTesting()) {
  59912. var alphaTexture = material.getAlphaTestTexture();
  59913. if (alphaTexture) {
  59914. defines.push("#define ALPHATEST");
  59915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59916. attribs.push(BABYLON.VertexBuffer.UVKind);
  59917. defines.push("#define UV1");
  59918. }
  59919. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59920. if (alphaTexture.coordinatesIndex === 1) {
  59921. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59922. defines.push("#define UV2");
  59923. }
  59924. }
  59925. }
  59926. }
  59927. // Bones
  59928. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59931. if (mesh.numBoneInfluencers > 4) {
  59932. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59933. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59934. }
  59935. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59936. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59937. }
  59938. else {
  59939. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59940. }
  59941. // Instances
  59942. if (useInstances) {
  59943. defines.push("#define INSTANCES");
  59944. attribs.push("world0");
  59945. attribs.push("world1");
  59946. attribs.push("world2");
  59947. attribs.push("world3");
  59948. }
  59949. // Get correct effect
  59950. var join = defines.join("\n");
  59951. if (this._cachedDefines !== join) {
  59952. this._cachedDefines = join;
  59953. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59954. }
  59955. if (!this._effect.isReady()) {
  59956. return false;
  59957. }
  59958. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59959. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59960. this._initializeBlurRTTAndPostProcesses();
  59961. }
  59962. }
  59963. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59964. return false;
  59965. }
  59966. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59967. return false;
  59968. }
  59969. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59970. return false;
  59971. }
  59972. return true;
  59973. };
  59974. /**
  59975. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59976. * @param defines Defines of the material we want to update
  59977. * @param lightIndex Index of the light in the enabled light list of the material
  59978. */
  59979. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59980. var scene = this._scene;
  59981. var light = this._light;
  59982. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59983. return;
  59984. }
  59985. defines["SHADOW" + lightIndex] = true;
  59986. if (this.usePoissonSampling) {
  59987. defines["SHADOWPCF" + lightIndex] = true;
  59988. }
  59989. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59990. defines["SHADOWESM" + lightIndex] = true;
  59991. }
  59992. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59993. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59994. }
  59995. if (light.needCube()) {
  59996. defines["SHADOWCUBE" + lightIndex] = true;
  59997. }
  59998. };
  59999. /**
  60000. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60001. * defined in the generator but impacting the effect).
  60002. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60003. * @param effect The effect we are binfing the information for
  60004. */
  60005. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60006. var light = this._light;
  60007. var scene = this._scene;
  60008. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60009. return;
  60010. }
  60011. var camera = scene.activeCamera;
  60012. if (!camera) {
  60013. return;
  60014. }
  60015. var shadowMap = this.getShadowMap();
  60016. if (!shadowMap) {
  60017. return;
  60018. }
  60019. if (!light.needCube()) {
  60020. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60021. }
  60022. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60023. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60024. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60025. };
  60026. /**
  60027. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60028. * (eq to shadow prjection matrix * light transform matrix)
  60029. * @returns The transform matrix used to create the shadow map
  60030. */
  60031. ShadowGenerator.prototype.getTransformMatrix = function () {
  60032. var scene = this._scene;
  60033. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60034. return this._transformMatrix;
  60035. }
  60036. this._currentRenderID = scene.getRenderId();
  60037. this._currentFaceIndexCache = this._currentFaceIndex;
  60038. var lightPosition = this._light.position;
  60039. if (this._light.computeTransformedInformation()) {
  60040. lightPosition = this._light.transformedPosition;
  60041. }
  60042. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60043. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60044. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60045. }
  60046. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60047. this._cachedPosition = lightPosition.clone();
  60048. this._cachedDirection = this._lightDirection.clone();
  60049. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60050. var shadowMap = this.getShadowMap();
  60051. if (shadowMap) {
  60052. var renderList = shadowMap.renderList;
  60053. if (renderList) {
  60054. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60055. }
  60056. }
  60057. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60058. }
  60059. return this._transformMatrix;
  60060. };
  60061. /**
  60062. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60063. * Cube and 2D textures for instance.
  60064. */
  60065. ShadowGenerator.prototype.recreateShadowMap = function () {
  60066. var shadowMap = this._shadowMap;
  60067. if (!shadowMap) {
  60068. return;
  60069. }
  60070. // Track render list.
  60071. var renderList = shadowMap.renderList;
  60072. // Clean up existing data.
  60073. this._disposeRTTandPostProcesses();
  60074. // Reinitializes.
  60075. this._initializeGenerator();
  60076. // Reaffect the filter to ensure a correct fallback if necessary.
  60077. this.filter = this.filter;
  60078. // Reaffect the filter.
  60079. this._applyFilterValues();
  60080. // Reaffect Render List.
  60081. this._shadowMap.renderList = renderList;
  60082. };
  60083. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60084. if (this._shadowMap2) {
  60085. this._shadowMap2.dispose();
  60086. this._shadowMap2 = null;
  60087. }
  60088. if (this._boxBlurPostprocess) {
  60089. this._boxBlurPostprocess.dispose();
  60090. this._boxBlurPostprocess = null;
  60091. }
  60092. if (this._kernelBlurXPostprocess) {
  60093. this._kernelBlurXPostprocess.dispose();
  60094. this._kernelBlurXPostprocess = null;
  60095. }
  60096. if (this._kernelBlurYPostprocess) {
  60097. this._kernelBlurYPostprocess.dispose();
  60098. this._kernelBlurYPostprocess = null;
  60099. }
  60100. this._blurPostProcesses = [];
  60101. };
  60102. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60103. if (this._shadowMap) {
  60104. this._shadowMap.dispose();
  60105. this._shadowMap = null;
  60106. }
  60107. this._disposeBlurPostProcesses();
  60108. };
  60109. /**
  60110. * Disposes the ShadowGenerator.
  60111. * Returns nothing.
  60112. */
  60113. ShadowGenerator.prototype.dispose = function () {
  60114. this._disposeRTTandPostProcesses();
  60115. if (this._light) {
  60116. this._light._shadowGenerator = null;
  60117. this._light._markMeshesAsLightDirty();
  60118. }
  60119. };
  60120. /**
  60121. * Serializes the shadow generator setup to a json object.
  60122. * @returns The serialized JSON object
  60123. */
  60124. ShadowGenerator.prototype.serialize = function () {
  60125. var serializationObject = {};
  60126. var shadowMap = this.getShadowMap();
  60127. if (!shadowMap) {
  60128. return serializationObject;
  60129. }
  60130. serializationObject.lightId = this._light.id;
  60131. serializationObject.mapSize = shadowMap.getRenderSize();
  60132. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60133. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60134. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60135. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60136. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60137. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60138. serializationObject.depthScale = this.depthScale;
  60139. serializationObject.darkness = this.getDarkness();
  60140. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60141. serializationObject.blurKernel = this.blurKernel;
  60142. serializationObject.blurScale = this.blurScale;
  60143. serializationObject.useKernelBlur = this.useKernelBlur;
  60144. serializationObject.transparencyShadow = this._transparencyShadow;
  60145. serializationObject.renderList = [];
  60146. if (shadowMap.renderList) {
  60147. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60148. var mesh = shadowMap.renderList[meshIndex];
  60149. serializationObject.renderList.push(mesh.id);
  60150. }
  60151. }
  60152. return serializationObject;
  60153. };
  60154. /**
  60155. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60156. * @param parsedShadowGenerator The JSON object to parse
  60157. * @param scene The scene to create the shadow map for
  60158. * @returns The parsed shadow generator
  60159. */
  60160. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60161. //casting to point light, as light is missing the position attr and typescript complains.
  60162. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60163. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60164. var shadowMap = shadowGenerator.getShadowMap();
  60165. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60166. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60167. meshes.forEach(function (mesh) {
  60168. if (!shadowMap) {
  60169. return;
  60170. }
  60171. if (!shadowMap.renderList) {
  60172. shadowMap.renderList = [];
  60173. }
  60174. shadowMap.renderList.push(mesh);
  60175. });
  60176. }
  60177. if (parsedShadowGenerator.usePoissonSampling) {
  60178. shadowGenerator.usePoissonSampling = true;
  60179. }
  60180. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60181. shadowGenerator.useExponentialShadowMap = true;
  60182. }
  60183. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60184. shadowGenerator.useBlurExponentialShadowMap = true;
  60185. }
  60186. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60187. shadowGenerator.useCloseExponentialShadowMap = true;
  60188. }
  60189. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60190. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60191. }
  60192. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60193. shadowGenerator.useExponentialShadowMap = true;
  60194. }
  60195. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60196. shadowGenerator.useBlurExponentialShadowMap = true;
  60197. }
  60198. if (parsedShadowGenerator.depthScale) {
  60199. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60200. }
  60201. if (parsedShadowGenerator.blurScale) {
  60202. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60203. }
  60204. if (parsedShadowGenerator.blurBoxOffset) {
  60205. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60206. }
  60207. if (parsedShadowGenerator.useKernelBlur) {
  60208. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60209. }
  60210. if (parsedShadowGenerator.blurKernel) {
  60211. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60212. }
  60213. if (parsedShadowGenerator.bias !== undefined) {
  60214. shadowGenerator.bias = parsedShadowGenerator.bias;
  60215. }
  60216. if (parsedShadowGenerator.darkness) {
  60217. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60218. }
  60219. if (parsedShadowGenerator.transparencyShadow) {
  60220. shadowGenerator.setTransparencyShadow(true);
  60221. }
  60222. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60223. return shadowGenerator;
  60224. };
  60225. ShadowGenerator._FILTER_NONE = 0;
  60226. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60227. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60228. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60229. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60230. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60231. return ShadowGenerator;
  60232. }());
  60233. BABYLON.ShadowGenerator = ShadowGenerator;
  60234. })(BABYLON || (BABYLON = {}));
  60235. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60236. var BABYLON;
  60237. (function (BABYLON) {
  60238. var DefaultLoadingScreen = /** @class */ (function () {
  60239. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60240. if (_loadingText === void 0) { _loadingText = ""; }
  60241. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60242. var _this = this;
  60243. this._renderingCanvas = _renderingCanvas;
  60244. this._loadingText = _loadingText;
  60245. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60246. // Resize
  60247. this._resizeLoadingUI = function () {
  60248. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60249. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60250. if (!_this._loadingDiv) {
  60251. return;
  60252. }
  60253. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60254. _this._loadingDiv.style.left = canvasRect.left + "px";
  60255. _this._loadingDiv.style.top = canvasRect.top + "px";
  60256. _this._loadingDiv.style.width = canvasRect.width + "px";
  60257. _this._loadingDiv.style.height = canvasRect.height + "px";
  60258. };
  60259. }
  60260. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60261. if (this._loadingDiv) {
  60262. // Do not add a loading screen if there is already one
  60263. return;
  60264. }
  60265. this._loadingDiv = document.createElement("div");
  60266. this._loadingDiv.id = "babylonjsLoadingDiv";
  60267. this._loadingDiv.style.opacity = "0";
  60268. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60269. this._loadingDiv.style.pointerEvents = "none";
  60270. // Loading text
  60271. this._loadingTextDiv = document.createElement("div");
  60272. this._loadingTextDiv.style.position = "absolute";
  60273. this._loadingTextDiv.style.left = "0";
  60274. this._loadingTextDiv.style.top = "50%";
  60275. this._loadingTextDiv.style.marginTop = "80px";
  60276. this._loadingTextDiv.style.width = "100%";
  60277. this._loadingTextDiv.style.height = "20px";
  60278. this._loadingTextDiv.style.fontFamily = "Arial";
  60279. this._loadingTextDiv.style.fontSize = "14px";
  60280. this._loadingTextDiv.style.color = "white";
  60281. this._loadingTextDiv.style.textAlign = "center";
  60282. this._loadingTextDiv.innerHTML = "Loading";
  60283. this._loadingDiv.appendChild(this._loadingTextDiv);
  60284. //set the predefined text
  60285. this._loadingTextDiv.innerHTML = this._loadingText;
  60286. // Generating keyframes
  60287. var style = document.createElement('style');
  60288. style.type = 'text/css';
  60289. 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 }";
  60290. style.innerHTML = keyFrames;
  60291. document.getElementsByTagName('head')[0].appendChild(style);
  60292. // Loading img
  60293. var imgBack = new Image();
  60294. 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";
  60295. imgBack.style.position = "absolute";
  60296. imgBack.style.left = "50%";
  60297. imgBack.style.top = "50%";
  60298. imgBack.style.marginLeft = "-60px";
  60299. imgBack.style.marginTop = "-60px";
  60300. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60301. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60302. imgBack.style.transformOrigin = "50% 50%";
  60303. imgBack.style.webkitTransformOrigin = "50% 50%";
  60304. this._loadingDiv.appendChild(imgBack);
  60305. this._resizeLoadingUI();
  60306. window.addEventListener("resize", this._resizeLoadingUI);
  60307. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60308. document.body.appendChild(this._loadingDiv);
  60309. this._loadingDiv.style.opacity = "1";
  60310. };
  60311. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60312. var _this = this;
  60313. if (!this._loadingDiv) {
  60314. return;
  60315. }
  60316. var onTransitionEnd = function () {
  60317. if (!_this._loadingDiv) {
  60318. return;
  60319. }
  60320. document.body.removeChild(_this._loadingDiv);
  60321. window.removeEventListener("resize", _this._resizeLoadingUI);
  60322. _this._loadingDiv = null;
  60323. };
  60324. this._loadingDiv.style.opacity = "0";
  60325. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60326. };
  60327. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60328. set: function (text) {
  60329. this._loadingText = text;
  60330. if (this._loadingTextDiv) {
  60331. this._loadingTextDiv.innerHTML = this._loadingText;
  60332. }
  60333. },
  60334. enumerable: true,
  60335. configurable: true
  60336. });
  60337. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60338. get: function () {
  60339. return this._loadingDivBackgroundColor;
  60340. },
  60341. set: function (color) {
  60342. this._loadingDivBackgroundColor = color;
  60343. if (!this._loadingDiv) {
  60344. return;
  60345. }
  60346. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60347. },
  60348. enumerable: true,
  60349. configurable: true
  60350. });
  60351. return DefaultLoadingScreen;
  60352. }());
  60353. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60354. })(BABYLON || (BABYLON = {}));
  60355. //# sourceMappingURL=babylon.loadingScreen.js.map
  60356. var BABYLON;
  60357. (function (BABYLON) {
  60358. var SceneLoaderProgressEvent = /** @class */ (function () {
  60359. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60360. this.lengthComputable = lengthComputable;
  60361. this.loaded = loaded;
  60362. this.total = total;
  60363. }
  60364. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60365. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60366. };
  60367. return SceneLoaderProgressEvent;
  60368. }());
  60369. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60370. var SceneLoader = /** @class */ (function () {
  60371. function SceneLoader() {
  60372. }
  60373. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60374. get: function () {
  60375. return 0;
  60376. },
  60377. enumerable: true,
  60378. configurable: true
  60379. });
  60380. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60381. get: function () {
  60382. return 1;
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60388. get: function () {
  60389. return 2;
  60390. },
  60391. enumerable: true,
  60392. configurable: true
  60393. });
  60394. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60395. get: function () {
  60396. return 3;
  60397. },
  60398. enumerable: true,
  60399. configurable: true
  60400. });
  60401. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60402. get: function () {
  60403. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60404. },
  60405. set: function (value) {
  60406. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60407. },
  60408. enumerable: true,
  60409. configurable: true
  60410. });
  60411. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60412. get: function () {
  60413. return SceneLoader._ShowLoadingScreen;
  60414. },
  60415. set: function (value) {
  60416. SceneLoader._ShowLoadingScreen = value;
  60417. },
  60418. enumerable: true,
  60419. configurable: true
  60420. });
  60421. Object.defineProperty(SceneLoader, "loggingLevel", {
  60422. get: function () {
  60423. return SceneLoader._loggingLevel;
  60424. },
  60425. set: function (value) {
  60426. SceneLoader._loggingLevel = value;
  60427. },
  60428. enumerable: true,
  60429. configurable: true
  60430. });
  60431. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60432. get: function () {
  60433. return SceneLoader._CleanBoneMatrixWeights;
  60434. },
  60435. set: function (value) {
  60436. SceneLoader._CleanBoneMatrixWeights = value;
  60437. },
  60438. enumerable: true,
  60439. configurable: true
  60440. });
  60441. SceneLoader._getDefaultPlugin = function () {
  60442. return SceneLoader._registeredPlugins[".babylon"];
  60443. };
  60444. SceneLoader._getPluginForExtension = function (extension) {
  60445. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60446. if (registeredPlugin) {
  60447. return registeredPlugin;
  60448. }
  60449. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60450. return SceneLoader._getDefaultPlugin();
  60451. };
  60452. SceneLoader._getPluginForDirectLoad = function (data) {
  60453. for (var extension in SceneLoader._registeredPlugins) {
  60454. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60455. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60456. return SceneLoader._registeredPlugins[extension];
  60457. }
  60458. }
  60459. return SceneLoader._getDefaultPlugin();
  60460. };
  60461. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60462. if (sceneFilename.name) {
  60463. sceneFilename = sceneFilename.name;
  60464. }
  60465. var queryStringPosition = sceneFilename.indexOf("?");
  60466. if (queryStringPosition !== -1) {
  60467. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60468. }
  60469. var dotPosition = sceneFilename.lastIndexOf(".");
  60470. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60471. return SceneLoader._getPluginForExtension(extension);
  60472. };
  60473. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60474. SceneLoader._getDirectLoad = function (sceneFilename) {
  60475. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60476. return sceneFilename.substr(5);
  60477. }
  60478. return null;
  60479. };
  60480. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60481. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60482. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60483. var plugin;
  60484. if (registeredPlugin.plugin.createPlugin) {
  60485. plugin = registeredPlugin.plugin.createPlugin();
  60486. }
  60487. else {
  60488. plugin = registeredPlugin.plugin;
  60489. }
  60490. var useArrayBuffer = registeredPlugin.isBinary;
  60491. var database;
  60492. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60493. var dataCallback = function (data, responseURL) {
  60494. if (scene.isDisposed) {
  60495. onError("Scene has been disposed");
  60496. return;
  60497. }
  60498. scene.database = database;
  60499. onSuccess(plugin, data, responseURL);
  60500. };
  60501. var request = null;
  60502. var pluginDisposed = false;
  60503. var onDisposeObservable = plugin.onDisposeObservable;
  60504. if (onDisposeObservable) {
  60505. onDisposeObservable.add(function () {
  60506. pluginDisposed = true;
  60507. if (request) {
  60508. request.abort();
  60509. request = null;
  60510. }
  60511. onDispose();
  60512. });
  60513. }
  60514. var manifestChecked = function () {
  60515. if (pluginDisposed) {
  60516. return;
  60517. }
  60518. var url = rootUrl + sceneFilename;
  60519. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60520. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60521. } : undefined, database, useArrayBuffer, function (request, exception) {
  60522. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60523. });
  60524. };
  60525. if (directLoad) {
  60526. dataCallback(directLoad);
  60527. return plugin;
  60528. }
  60529. if (rootUrl.indexOf("file:") === -1) {
  60530. if (scene.getEngine().enableOfflineSupport) {
  60531. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60532. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60533. }
  60534. else {
  60535. manifestChecked();
  60536. }
  60537. }
  60538. else {
  60539. var fileOrString = sceneFilename;
  60540. if (fileOrString.name) {
  60541. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60542. }
  60543. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60544. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60545. }
  60546. else {
  60547. onError("Unable to find file named " + sceneFilename);
  60548. }
  60549. }
  60550. return plugin;
  60551. };
  60552. // Public functions
  60553. SceneLoader.GetPluginForExtension = function (extension) {
  60554. return SceneLoader._getPluginForExtension(extension).plugin;
  60555. };
  60556. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60557. return !!SceneLoader._registeredPlugins[extension];
  60558. };
  60559. SceneLoader.RegisterPlugin = function (plugin) {
  60560. if (typeof plugin.extensions === "string") {
  60561. var extension = plugin.extensions;
  60562. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60563. plugin: plugin,
  60564. isBinary: false
  60565. };
  60566. }
  60567. else {
  60568. var extensions = plugin.extensions;
  60569. Object.keys(extensions).forEach(function (extension) {
  60570. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60571. plugin: plugin,
  60572. isBinary: extensions[extension].isBinary
  60573. };
  60574. });
  60575. }
  60576. };
  60577. /**
  60578. * Import meshes into a scene
  60579. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60580. * @param rootUrl a string that defines the root url for scene and resources
  60581. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60582. * @param scene the instance of BABYLON.Scene to append to
  60583. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60584. * @param onProgress a callback with a progress event for each file being loaded
  60585. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60586. * @param pluginExtension the extension used to determine the plugin
  60587. * @returns The loaded plugin
  60588. */
  60589. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60590. if (onSuccess === void 0) { onSuccess = null; }
  60591. if (onProgress === void 0) { onProgress = null; }
  60592. if (onError === void 0) { onError = null; }
  60593. if (pluginExtension === void 0) { pluginExtension = null; }
  60594. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60595. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60596. return null;
  60597. }
  60598. var loadingToken = {};
  60599. scene._addPendingData(loadingToken);
  60600. var disposeHandler = function () {
  60601. scene._removePendingData(loadingToken);
  60602. };
  60603. var errorHandler = function (message, exception) {
  60604. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60605. if (onError) {
  60606. onError(scene, errorMessage, exception);
  60607. }
  60608. else {
  60609. BABYLON.Tools.Error(errorMessage);
  60610. // should the exception be thrown?
  60611. }
  60612. disposeHandler();
  60613. };
  60614. var progressHandler = onProgress ? function (event) {
  60615. try {
  60616. onProgress(event);
  60617. }
  60618. catch (e) {
  60619. errorHandler("Error in onProgress callback", e);
  60620. }
  60621. } : undefined;
  60622. var successHandler = function (meshes, particleSystems, skeletons) {
  60623. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60624. if (onSuccess) {
  60625. try {
  60626. onSuccess(meshes, particleSystems, skeletons);
  60627. }
  60628. catch (e) {
  60629. errorHandler("Error in onSuccess callback", e);
  60630. }
  60631. }
  60632. scene._removePendingData(loadingToken);
  60633. };
  60634. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60635. if (plugin.rewriteRootURL) {
  60636. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60637. }
  60638. if (sceneFilename === "") {
  60639. if (sceneFilename === "") {
  60640. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60641. }
  60642. }
  60643. if (plugin.importMesh) {
  60644. var syncedPlugin = plugin;
  60645. var meshes = new Array();
  60646. var particleSystems = new Array();
  60647. var skeletons = new Array();
  60648. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60649. return;
  60650. }
  60651. scene.loadingPluginName = plugin.name;
  60652. successHandler(meshes, particleSystems, skeletons);
  60653. }
  60654. else {
  60655. var asyncedPlugin = plugin;
  60656. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60657. scene.loadingPluginName = plugin.name;
  60658. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60659. }).catch(function (error) {
  60660. errorHandler(error.message, error);
  60661. });
  60662. }
  60663. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60664. };
  60665. /**
  60666. * Import meshes into a scene
  60667. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60668. * @param rootUrl a string that defines the root url for scene and resources
  60669. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60670. * @param scene the instance of BABYLON.Scene to append to
  60671. * @param onProgress a callback with a progress event for each file being loaded
  60672. * @param pluginExtension the extension used to determine the plugin
  60673. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60674. */
  60675. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60676. if (onProgress === void 0) { onProgress = null; }
  60677. if (pluginExtension === void 0) { pluginExtension = null; }
  60678. return new Promise(function (resolve, reject) {
  60679. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60680. resolve({
  60681. meshes: meshes,
  60682. particleSystems: particleSystems,
  60683. skeletons: skeletons
  60684. });
  60685. }, onProgress, function (scene, message, exception) {
  60686. reject(exception || new Error(message));
  60687. });
  60688. });
  60689. };
  60690. /**
  60691. * Load a scene
  60692. * @param rootUrl a string that defines the root url for scene and resources
  60693. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60694. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60695. * @param onSuccess a callback with the scene when import succeeds
  60696. * @param onProgress a callback with a progress event for each file being loaded
  60697. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60698. * @param pluginExtension the extension used to determine the plugin
  60699. * @returns The loaded plugin
  60700. */
  60701. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60702. if (onSuccess === void 0) { onSuccess = null; }
  60703. if (onProgress === void 0) { onProgress = null; }
  60704. if (onError === void 0) { onError = null; }
  60705. if (pluginExtension === void 0) { pluginExtension = null; }
  60706. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60707. };
  60708. /**
  60709. * Load a scene
  60710. * @param rootUrl a string that defines the root url for scene and resources
  60711. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60712. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60713. * @param onProgress a callback with a progress event for each file being loaded
  60714. * @param pluginExtension the extension used to determine the plugin
  60715. * @returns The loaded scene
  60716. */
  60717. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60718. if (onProgress === void 0) { onProgress = null; }
  60719. if (pluginExtension === void 0) { pluginExtension = null; }
  60720. return new Promise(function (resolve, reject) {
  60721. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60722. resolve(scene);
  60723. }, onProgress, function (scene, message, exception) {
  60724. reject(exception || new Error(message));
  60725. }, pluginExtension);
  60726. });
  60727. };
  60728. /**
  60729. * Append a scene
  60730. * @param rootUrl a string that defines the root url for scene and resources
  60731. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60732. * @param scene is the instance of BABYLON.Scene to append to
  60733. * @param onSuccess a callback with the scene when import succeeds
  60734. * @param onProgress a callback with a progress event for each file being loaded
  60735. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60736. * @param pluginExtension the extension used to determine the plugin
  60737. * @returns The loaded plugin
  60738. */
  60739. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60740. if (onSuccess === void 0) { onSuccess = null; }
  60741. if (onProgress === void 0) { onProgress = null; }
  60742. if (onError === void 0) { onError = null; }
  60743. if (pluginExtension === void 0) { pluginExtension = null; }
  60744. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60745. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60746. return null;
  60747. }
  60748. if (SceneLoader.ShowLoadingScreen) {
  60749. scene.getEngine().displayLoadingUI();
  60750. }
  60751. var loadingToken = {};
  60752. scene._addPendingData(loadingToken);
  60753. var disposeHandler = function () {
  60754. scene._removePendingData(loadingToken);
  60755. scene.getEngine().hideLoadingUI();
  60756. };
  60757. var errorHandler = function (message, exception) {
  60758. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60759. if (onError) {
  60760. onError(scene, errorMessage, exception);
  60761. }
  60762. else {
  60763. BABYLON.Tools.Error(errorMessage);
  60764. // should the exception be thrown?
  60765. }
  60766. disposeHandler();
  60767. };
  60768. var progressHandler = onProgress ? function (event) {
  60769. try {
  60770. onProgress(event);
  60771. }
  60772. catch (e) {
  60773. errorHandler("Error in onProgress callback", e);
  60774. }
  60775. } : undefined;
  60776. var successHandler = function () {
  60777. if (onSuccess) {
  60778. try {
  60779. onSuccess(scene);
  60780. }
  60781. catch (e) {
  60782. errorHandler("Error in onSuccess callback", e);
  60783. }
  60784. }
  60785. scene._removePendingData(loadingToken);
  60786. };
  60787. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60788. if (sceneFilename === "") {
  60789. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60790. }
  60791. if (plugin.load) {
  60792. var syncedPlugin = plugin;
  60793. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60794. return;
  60795. }
  60796. scene.loadingPluginName = plugin.name;
  60797. successHandler();
  60798. }
  60799. else {
  60800. var asyncedPlugin = plugin;
  60801. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60802. scene.loadingPluginName = plugin.name;
  60803. successHandler();
  60804. }).catch(function (error) {
  60805. errorHandler(error.message, error);
  60806. });
  60807. }
  60808. if (SceneLoader.ShowLoadingScreen) {
  60809. scene.executeWhenReady(function () {
  60810. scene.getEngine().hideLoadingUI();
  60811. });
  60812. }
  60813. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60814. };
  60815. /**
  60816. * Append a scene
  60817. * @param rootUrl a string that defines the root url for scene and resources
  60818. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60819. * @param scene is the instance of BABYLON.Scene to append to
  60820. * @param onProgress a callback with a progress event for each file being loaded
  60821. * @param pluginExtension the extension used to determine the plugin
  60822. * @returns The given scene
  60823. */
  60824. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60825. if (onProgress === void 0) { onProgress = null; }
  60826. if (pluginExtension === void 0) { pluginExtension = null; }
  60827. return new Promise(function (resolve, reject) {
  60828. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60829. resolve(scene);
  60830. }, onProgress, function (scene, message, exception) {
  60831. reject(exception || new Error(message));
  60832. }, pluginExtension);
  60833. });
  60834. };
  60835. /**
  60836. * Load a scene into an asset container
  60837. * @param rootUrl a string that defines the root url for scene and resources
  60838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60839. * @param scene is the instance of BABYLON.Scene to append to
  60840. * @param onSuccess a callback with the scene when import succeeds
  60841. * @param onProgress a callback with a progress event for each file being loaded
  60842. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60843. * @param pluginExtension the extension used to determine the plugin
  60844. * @returns The loaded plugin
  60845. */
  60846. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60847. if (onSuccess === void 0) { onSuccess = null; }
  60848. if (onProgress === void 0) { onProgress = null; }
  60849. if (onError === void 0) { onError = null; }
  60850. if (pluginExtension === void 0) { pluginExtension = null; }
  60851. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60852. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60853. return null;
  60854. }
  60855. var loadingToken = {};
  60856. scene._addPendingData(loadingToken);
  60857. var disposeHandler = function () {
  60858. scene._removePendingData(loadingToken);
  60859. };
  60860. var errorHandler = function (message, exception) {
  60861. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60862. if (onError) {
  60863. onError(scene, errorMessage, exception);
  60864. }
  60865. else {
  60866. BABYLON.Tools.Error(errorMessage);
  60867. // should the exception be thrown?
  60868. }
  60869. disposeHandler();
  60870. };
  60871. var progressHandler = onProgress ? function (event) {
  60872. try {
  60873. onProgress(event);
  60874. }
  60875. catch (e) {
  60876. errorHandler("Error in onProgress callback", e);
  60877. }
  60878. } : undefined;
  60879. var successHandler = function (assets) {
  60880. if (onSuccess) {
  60881. try {
  60882. onSuccess(assets);
  60883. }
  60884. catch (e) {
  60885. errorHandler("Error in onSuccess callback", e);
  60886. }
  60887. }
  60888. scene._removePendingData(loadingToken);
  60889. };
  60890. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60891. if (plugin.loadAssetContainer) {
  60892. var syncedPlugin = plugin;
  60893. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60894. if (!assetContainer) {
  60895. return;
  60896. }
  60897. scene.loadingPluginName = plugin.name;
  60898. successHandler(assetContainer);
  60899. }
  60900. else if (plugin.loadAssetContainerAsync) {
  60901. var asyncedPlugin = plugin;
  60902. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60903. scene.loadingPluginName = plugin.name;
  60904. successHandler(assetContainer);
  60905. }).catch(function (error) {
  60906. errorHandler(error.message, error);
  60907. });
  60908. }
  60909. else {
  60910. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60911. }
  60912. if (SceneLoader.ShowLoadingScreen) {
  60913. scene.executeWhenReady(function () {
  60914. scene.getEngine().hideLoadingUI();
  60915. });
  60916. }
  60917. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60918. };
  60919. /**
  60920. * Load a scene into an asset container
  60921. * @param rootUrl a string that defines the root url for scene and resources
  60922. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60923. * @param scene is the instance of BABYLON.Scene to append to
  60924. * @param onProgress a callback with a progress event for each file being loaded
  60925. * @param pluginExtension the extension used to determine the plugin
  60926. * @returns The loaded asset container
  60927. */
  60928. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60929. if (onProgress === void 0) { onProgress = null; }
  60930. if (pluginExtension === void 0) { pluginExtension = null; }
  60931. return new Promise(function (resolve, reject) {
  60932. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60933. resolve(assetContainer);
  60934. }, onProgress, function (scene, message, exception) {
  60935. reject(exception || new Error(message));
  60936. }, pluginExtension);
  60937. });
  60938. };
  60939. // Flags
  60940. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60941. SceneLoader._ShowLoadingScreen = true;
  60942. SceneLoader._CleanBoneMatrixWeights = false;
  60943. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60944. // Members
  60945. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60946. SceneLoader._registeredPlugins = {};
  60947. return SceneLoader;
  60948. }());
  60949. BABYLON.SceneLoader = SceneLoader;
  60950. ;
  60951. })(BABYLON || (BABYLON = {}));
  60952. //# sourceMappingURL=babylon.sceneLoader.js.map
  60953. var BABYLON;
  60954. (function (BABYLON) {
  60955. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60956. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60957. var parsedMaterial = parsedData.materials[index];
  60958. if (parsedMaterial.id === id) {
  60959. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60960. }
  60961. }
  60962. return null;
  60963. };
  60964. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60965. for (var i in names) {
  60966. if (mesh.name === names[i]) {
  60967. hierarchyIds.push(mesh.id);
  60968. return true;
  60969. }
  60970. }
  60971. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60972. hierarchyIds.push(mesh.id);
  60973. return true;
  60974. }
  60975. return false;
  60976. };
  60977. var logOperation = function (operation, producer) {
  60978. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60979. };
  60980. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60981. if (addToScene === void 0) { addToScene = false; }
  60982. var container = new BABYLON.AssetContainer(scene);
  60983. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60984. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60985. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60986. // and avoid problems with multiple concurrent .babylon loads.
  60987. var log = "importScene has failed JSON parse";
  60988. try {
  60989. var parsedData = JSON.parse(data);
  60990. log = "";
  60991. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60992. var index;
  60993. var cache;
  60994. // Lights
  60995. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60996. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60997. var parsedLight = parsedData.lights[index];
  60998. var light = BABYLON.Light.Parse(parsedLight, scene);
  60999. if (light) {
  61000. container.lights.push(light);
  61001. log += (index === 0 ? "\n\tLights:" : "");
  61002. log += "\n\t\t" + light.toString(fullDetails);
  61003. }
  61004. }
  61005. }
  61006. // Animations
  61007. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61008. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61009. var parsedAnimation = parsedData.animations[index];
  61010. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61011. scene.animations.push(animation);
  61012. container.animations.push(animation);
  61013. log += (index === 0 ? "\n\tAnimations:" : "");
  61014. log += "\n\t\t" + animation.toString(fullDetails);
  61015. }
  61016. }
  61017. // Materials
  61018. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61019. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61020. var parsedMaterial = parsedData.materials[index];
  61021. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61022. container.materials.push(mat);
  61023. log += (index === 0 ? "\n\tMaterials:" : "");
  61024. log += "\n\t\t" + mat.toString(fullDetails);
  61025. }
  61026. }
  61027. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61028. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61029. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61030. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61031. container.multiMaterials.push(mmat);
  61032. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61033. log += "\n\t\t" + mmat.toString(fullDetails);
  61034. }
  61035. }
  61036. // Morph targets
  61037. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61038. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61039. var managerData = _a[_i];
  61040. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61041. }
  61042. }
  61043. // Skeletons
  61044. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61045. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61046. var parsedSkeleton = parsedData.skeletons[index];
  61047. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61048. container.skeletons.push(skeleton);
  61049. log += (index === 0 ? "\n\tSkeletons:" : "");
  61050. log += "\n\t\t" + skeleton.toString(fullDetails);
  61051. }
  61052. }
  61053. // Geometries
  61054. var geometries = parsedData.geometries;
  61055. if (geometries !== undefined && geometries !== null) {
  61056. var addedGeometry = new Array();
  61057. // Boxes
  61058. var boxes = geometries.boxes;
  61059. if (boxes !== undefined && boxes !== null) {
  61060. for (index = 0, cache = boxes.length; index < cache; index++) {
  61061. var parsedBox = boxes[index];
  61062. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61063. }
  61064. }
  61065. // Spheres
  61066. var spheres = geometries.spheres;
  61067. if (spheres !== undefined && spheres !== null) {
  61068. for (index = 0, cache = spheres.length; index < cache; index++) {
  61069. var parsedSphere = spheres[index];
  61070. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61071. }
  61072. }
  61073. // Cylinders
  61074. var cylinders = geometries.cylinders;
  61075. if (cylinders !== undefined && cylinders !== null) {
  61076. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61077. var parsedCylinder = cylinders[index];
  61078. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61079. }
  61080. }
  61081. // Toruses
  61082. var toruses = geometries.toruses;
  61083. if (toruses !== undefined && toruses !== null) {
  61084. for (index = 0, cache = toruses.length; index < cache; index++) {
  61085. var parsedTorus = toruses[index];
  61086. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61087. }
  61088. }
  61089. // Grounds
  61090. var grounds = geometries.grounds;
  61091. if (grounds !== undefined && grounds !== null) {
  61092. for (index = 0, cache = grounds.length; index < cache; index++) {
  61093. var parsedGround = grounds[index];
  61094. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61095. }
  61096. }
  61097. // Planes
  61098. var planes = geometries.planes;
  61099. if (planes !== undefined && planes !== null) {
  61100. for (index = 0, cache = planes.length; index < cache; index++) {
  61101. var parsedPlane = planes[index];
  61102. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61103. }
  61104. }
  61105. // TorusKnots
  61106. var torusKnots = geometries.torusKnots;
  61107. if (torusKnots !== undefined && torusKnots !== null) {
  61108. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61109. var parsedTorusKnot = torusKnots[index];
  61110. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61111. }
  61112. }
  61113. // VertexData
  61114. var vertexData = geometries.vertexData;
  61115. if (vertexData !== undefined && vertexData !== null) {
  61116. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61117. var parsedVertexData = vertexData[index];
  61118. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61119. }
  61120. }
  61121. addedGeometry.forEach(function (g) {
  61122. if (g) {
  61123. container.geometries.push(g);
  61124. }
  61125. });
  61126. }
  61127. // Transform nodes
  61128. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61129. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61130. var parsedTransformNode = parsedData.transformNodes[index];
  61131. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61132. container.transformNodes.push(node);
  61133. }
  61134. }
  61135. // Meshes
  61136. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61137. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61138. var parsedMesh = parsedData.meshes[index];
  61139. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61140. container.meshes.push(mesh);
  61141. log += (index === 0 ? "\n\tMeshes:" : "");
  61142. log += "\n\t\t" + mesh.toString(fullDetails);
  61143. }
  61144. }
  61145. // Cameras
  61146. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61147. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61148. var parsedCamera = parsedData.cameras[index];
  61149. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61150. container.cameras.push(camera);
  61151. log += (index === 0 ? "\n\tCameras:" : "");
  61152. log += "\n\t\t" + camera.toString(fullDetails);
  61153. }
  61154. }
  61155. // Browsing all the graph to connect the dots
  61156. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61157. var camera = scene.cameras[index];
  61158. if (camera._waitingParentId) {
  61159. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61160. camera._waitingParentId = null;
  61161. }
  61162. }
  61163. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61164. var light_1 = scene.lights[index];
  61165. if (light_1 && light_1._waitingParentId) {
  61166. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61167. light_1._waitingParentId = null;
  61168. }
  61169. }
  61170. // Sounds
  61171. // TODO: add sound
  61172. var loadedSounds = [];
  61173. var loadedSound;
  61174. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61175. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61176. var parsedSound = parsedData.sounds[index];
  61177. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61178. if (!parsedSound.url)
  61179. parsedSound.url = parsedSound.name;
  61180. if (!loadedSounds[parsedSound.url]) {
  61181. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61182. loadedSounds[parsedSound.url] = loadedSound;
  61183. container.sounds.push(loadedSound);
  61184. }
  61185. else {
  61186. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61187. }
  61188. }
  61189. else {
  61190. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61191. }
  61192. }
  61193. }
  61194. loadedSounds = [];
  61195. // Connect parents & children and parse actions
  61196. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61197. var transformNode = scene.transformNodes[index];
  61198. if (transformNode._waitingParentId) {
  61199. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61200. transformNode._waitingParentId = null;
  61201. }
  61202. }
  61203. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61204. var mesh = scene.meshes[index];
  61205. if (mesh._waitingParentId) {
  61206. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61207. mesh._waitingParentId = null;
  61208. }
  61209. if (mesh._waitingActions) {
  61210. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61211. mesh._waitingActions = null;
  61212. }
  61213. }
  61214. // freeze world matrix application
  61215. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61216. var currentMesh = scene.meshes[index];
  61217. if (currentMesh._waitingFreezeWorldMatrix) {
  61218. currentMesh.freezeWorldMatrix();
  61219. currentMesh._waitingFreezeWorldMatrix = null;
  61220. }
  61221. else {
  61222. currentMesh.computeWorldMatrix(true);
  61223. }
  61224. }
  61225. // Particles Systems
  61226. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61227. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61228. var parsedParticleSystem = parsedData.particleSystems[index];
  61229. if (parsedParticleSystem.activeParticleCount) {
  61230. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61231. container.particleSystems.push(ps);
  61232. }
  61233. else {
  61234. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61235. container.particleSystems.push(ps);
  61236. }
  61237. }
  61238. }
  61239. // Lens flares
  61240. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61241. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61242. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61243. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61244. container.lensFlareSystems.push(lf);
  61245. }
  61246. }
  61247. // Shadows
  61248. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61249. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61250. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61251. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61252. container.shadowGenerators.push(sg);
  61253. }
  61254. }
  61255. // Lights exclusions / inclusions
  61256. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61257. var light_2 = scene.lights[index];
  61258. // Excluded check
  61259. if (light_2._excludedMeshesIds.length > 0) {
  61260. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61261. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61262. if (excludedMesh) {
  61263. light_2.excludedMeshes.push(excludedMesh);
  61264. }
  61265. }
  61266. light_2._excludedMeshesIds = [];
  61267. }
  61268. // Included check
  61269. if (light_2._includedOnlyMeshesIds.length > 0) {
  61270. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61271. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61272. if (includedOnlyMesh) {
  61273. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61274. }
  61275. }
  61276. light_2._includedOnlyMeshesIds = [];
  61277. }
  61278. }
  61279. // Actions (scene)
  61280. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61281. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61282. }
  61283. if (!addToScene) {
  61284. container.removeAllFromScene();
  61285. }
  61286. }
  61287. catch (err) {
  61288. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61289. if (onError) {
  61290. onError(msg, err);
  61291. }
  61292. else {
  61293. BABYLON.Tools.Log(msg);
  61294. throw err;
  61295. }
  61296. }
  61297. finally {
  61298. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61299. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61300. }
  61301. }
  61302. return container;
  61303. };
  61304. BABYLON.SceneLoader.RegisterPlugin({
  61305. name: "babylon.js",
  61306. extensions: ".babylon",
  61307. canDirectLoad: function (data) {
  61308. if (data.indexOf("babylon") !== -1) {
  61309. return true;
  61310. }
  61311. return false;
  61312. },
  61313. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61314. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61315. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61316. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61317. // and avoid problems with multiple concurrent .babylon loads.
  61318. var log = "importMesh has failed JSON parse";
  61319. try {
  61320. var parsedData = JSON.parse(data);
  61321. log = "";
  61322. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61323. if (!meshesNames) {
  61324. meshesNames = null;
  61325. }
  61326. else if (!Array.isArray(meshesNames)) {
  61327. meshesNames = [meshesNames];
  61328. }
  61329. var hierarchyIds = new Array();
  61330. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61331. var loadedSkeletonsIds = [];
  61332. var loadedMaterialsIds = [];
  61333. var index;
  61334. var cache;
  61335. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61336. var parsedMesh = parsedData.meshes[index];
  61337. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61338. if (meshesNames !== null) {
  61339. // Remove found mesh name from list.
  61340. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61341. }
  61342. //Geometry?
  61343. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61344. //does the file contain geometries?
  61345. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61346. //find the correct geometry and add it to the scene
  61347. var found = false;
  61348. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61349. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61350. return;
  61351. }
  61352. else {
  61353. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61354. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61355. switch (geometryType) {
  61356. case "boxes":
  61357. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61358. break;
  61359. case "spheres":
  61360. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61361. break;
  61362. case "cylinders":
  61363. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61364. break;
  61365. case "toruses":
  61366. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61367. break;
  61368. case "grounds":
  61369. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61370. break;
  61371. case "planes":
  61372. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61373. break;
  61374. case "torusKnots":
  61375. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61376. break;
  61377. case "vertexData":
  61378. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61379. break;
  61380. }
  61381. found = true;
  61382. }
  61383. });
  61384. }
  61385. });
  61386. if (found === false) {
  61387. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61388. }
  61389. }
  61390. }
  61391. // Material ?
  61392. if (parsedMesh.materialId) {
  61393. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61394. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61395. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61396. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61397. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61398. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61399. var subMatId = parsedMultiMaterial.materials[matIndex];
  61400. loadedMaterialsIds.push(subMatId);
  61401. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61402. if (mat) {
  61403. log += "\n\tMaterial " + mat.toString(fullDetails);
  61404. }
  61405. }
  61406. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61407. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61408. if (mmat) {
  61409. materialFound = true;
  61410. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61411. }
  61412. break;
  61413. }
  61414. }
  61415. }
  61416. if (materialFound === false) {
  61417. loadedMaterialsIds.push(parsedMesh.materialId);
  61418. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61419. if (!mat) {
  61420. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61421. }
  61422. else {
  61423. log += "\n\tMaterial " + mat.toString(fullDetails);
  61424. }
  61425. }
  61426. }
  61427. // Skeleton ?
  61428. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61429. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61430. if (skeletonAlreadyLoaded === false) {
  61431. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61432. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61433. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61434. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61435. skeletons.push(skeleton);
  61436. loadedSkeletonsIds.push(parsedSkeleton.id);
  61437. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61438. }
  61439. }
  61440. }
  61441. }
  61442. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61443. meshes.push(mesh);
  61444. log += "\n\tMesh " + mesh.toString(fullDetails);
  61445. }
  61446. }
  61447. // Connecting parents
  61448. var currentMesh;
  61449. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61450. currentMesh = scene.meshes[index];
  61451. if (currentMesh._waitingParentId) {
  61452. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61453. currentMesh._waitingParentId = null;
  61454. }
  61455. }
  61456. // freeze and compute world matrix application
  61457. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61458. currentMesh = scene.meshes[index];
  61459. if (currentMesh._waitingFreezeWorldMatrix) {
  61460. currentMesh.freezeWorldMatrix();
  61461. currentMesh._waitingFreezeWorldMatrix = null;
  61462. }
  61463. else {
  61464. currentMesh.computeWorldMatrix(true);
  61465. }
  61466. }
  61467. }
  61468. // Particles
  61469. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61470. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61471. var parsedParticleSystem = parsedData.particleSystems[index];
  61472. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61473. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61474. }
  61475. }
  61476. }
  61477. return true;
  61478. }
  61479. catch (err) {
  61480. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61481. if (onError) {
  61482. onError(msg, err);
  61483. }
  61484. else {
  61485. BABYLON.Tools.Log(msg);
  61486. throw err;
  61487. }
  61488. }
  61489. finally {
  61490. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61491. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61492. }
  61493. }
  61494. return false;
  61495. },
  61496. load: function (scene, data, rootUrl, onError) {
  61497. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61498. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61499. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61500. // and avoid problems with multiple concurrent .babylon loads.
  61501. var log = "importScene has failed JSON parse";
  61502. try {
  61503. var parsedData = JSON.parse(data);
  61504. log = "";
  61505. // Scene
  61506. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61507. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61508. }
  61509. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61510. scene.autoClear = parsedData.autoClear;
  61511. }
  61512. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61513. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61514. }
  61515. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61516. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61517. }
  61518. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61519. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61520. }
  61521. // Fog
  61522. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61523. scene.fogMode = parsedData.fogMode;
  61524. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61525. scene.fogStart = parsedData.fogStart;
  61526. scene.fogEnd = parsedData.fogEnd;
  61527. scene.fogDensity = parsedData.fogDensity;
  61528. log += "\tFog mode for scene: ";
  61529. switch (scene.fogMode) {
  61530. // getters not compiling, so using hardcoded
  61531. case 1:
  61532. log += "exp\n";
  61533. break;
  61534. case 2:
  61535. log += "exp2\n";
  61536. break;
  61537. case 3:
  61538. log += "linear\n";
  61539. break;
  61540. }
  61541. }
  61542. //Physics
  61543. if (parsedData.physicsEnabled) {
  61544. var physicsPlugin;
  61545. if (parsedData.physicsEngine === "cannon") {
  61546. physicsPlugin = new BABYLON.CannonJSPlugin();
  61547. }
  61548. else if (parsedData.physicsEngine === "oimo") {
  61549. physicsPlugin = new BABYLON.OimoJSPlugin();
  61550. }
  61551. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61552. //else - default engine, which is currently oimo
  61553. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61554. scene.enablePhysics(physicsGravity, physicsPlugin);
  61555. }
  61556. // Metadata
  61557. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61558. scene.metadata = parsedData.metadata;
  61559. }
  61560. //collisions, if defined. otherwise, default is true
  61561. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61562. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61563. }
  61564. scene.workerCollisions = !!parsedData.workerCollisions;
  61565. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61566. if (!container) {
  61567. return false;
  61568. }
  61569. if (parsedData.autoAnimate) {
  61570. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61571. }
  61572. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61573. scene.setActiveCameraByID(parsedData.activeCameraID);
  61574. }
  61575. // Environment texture
  61576. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61577. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61578. if (parsedData.createDefaultSkybox === true) {
  61579. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61580. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61581. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61582. }
  61583. }
  61584. // Finish
  61585. return true;
  61586. }
  61587. catch (err) {
  61588. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61589. if (onError) {
  61590. onError(msg, err);
  61591. }
  61592. else {
  61593. BABYLON.Tools.Log(msg);
  61594. throw err;
  61595. }
  61596. }
  61597. finally {
  61598. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61599. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61600. }
  61601. }
  61602. return false;
  61603. },
  61604. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61605. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61606. return container;
  61607. }
  61608. });
  61609. })(BABYLON || (BABYLON = {}));
  61610. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61611. var BABYLON;
  61612. (function (BABYLON) {
  61613. var FilesInput = /** @class */ (function () {
  61614. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61615. this.onProcessFileCallback = function () { return true; };
  61616. this._engine = engine;
  61617. this._currentScene = scene;
  61618. this._sceneLoadedCallback = sceneLoadedCallback;
  61619. this._progressCallback = progressCallback;
  61620. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61621. this._textureLoadingCallback = textureLoadingCallback;
  61622. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61623. this._onReloadCallback = onReloadCallback;
  61624. this._errorCallback = errorCallback;
  61625. }
  61626. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61627. var _this = this;
  61628. if (elementToMonitor) {
  61629. this._elementToMonitor = elementToMonitor;
  61630. this._dragEnterHandler = function (e) { _this.drag(e); };
  61631. this._dragOverHandler = function (e) { _this.drag(e); };
  61632. this._dropHandler = function (e) { _this.drop(e); };
  61633. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61634. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61635. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61636. }
  61637. };
  61638. FilesInput.prototype.dispose = function () {
  61639. if (!this._elementToMonitor) {
  61640. return;
  61641. }
  61642. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61643. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61644. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61645. };
  61646. FilesInput.prototype.renderFunction = function () {
  61647. if (this._additionalRenderLoopLogicCallback) {
  61648. this._additionalRenderLoopLogicCallback();
  61649. }
  61650. if (this._currentScene) {
  61651. if (this._textureLoadingCallback) {
  61652. var remaining = this._currentScene.getWaitingItemsCount();
  61653. if (remaining > 0) {
  61654. this._textureLoadingCallback(remaining);
  61655. }
  61656. }
  61657. this._currentScene.render();
  61658. }
  61659. };
  61660. FilesInput.prototype.drag = function (e) {
  61661. e.stopPropagation();
  61662. e.preventDefault();
  61663. };
  61664. FilesInput.prototype.drop = function (eventDrop) {
  61665. eventDrop.stopPropagation();
  61666. eventDrop.preventDefault();
  61667. this.loadFiles(eventDrop);
  61668. };
  61669. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61670. var _this = this;
  61671. var reader = folder.createReader();
  61672. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61673. reader.readEntries(function (entries) {
  61674. remaining.count += entries.length;
  61675. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61676. var entry = entries_1[_i];
  61677. if (entry.isFile) {
  61678. entry.file(function (file) {
  61679. file.correctName = relativePath + file.name;
  61680. files.push(file);
  61681. if (--remaining.count === 0) {
  61682. callback();
  61683. }
  61684. });
  61685. }
  61686. else if (entry.isDirectory) {
  61687. _this._traverseFolder(entry, files, remaining, callback);
  61688. }
  61689. }
  61690. if (--remaining.count) {
  61691. callback();
  61692. }
  61693. });
  61694. };
  61695. FilesInput.prototype._processFiles = function (files) {
  61696. for (var i = 0; i < files.length; i++) {
  61697. var name = files[i].correctName.toLowerCase();
  61698. var extension = name.split('.').pop();
  61699. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61700. continue;
  61701. }
  61702. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61703. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61704. this._sceneFileToLoad = files[i];
  61705. }
  61706. else {
  61707. FilesInput.FilesToLoad[name] = files[i];
  61708. }
  61709. }
  61710. };
  61711. FilesInput.prototype.loadFiles = function (event) {
  61712. var _this = this;
  61713. if (this._startingProcessingFilesCallback)
  61714. this._startingProcessingFilesCallback();
  61715. // Handling data transfer via drag'n'drop
  61716. if (event && event.dataTransfer && event.dataTransfer.files) {
  61717. this._filesToLoad = event.dataTransfer.files;
  61718. }
  61719. // Handling files from input files
  61720. if (event && event.target && event.target.files) {
  61721. this._filesToLoad = event.target.files;
  61722. }
  61723. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61724. var files_1 = new Array();
  61725. var folders = [];
  61726. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61727. for (var i = 0; i < this._filesToLoad.length; i++) {
  61728. var fileToLoad = this._filesToLoad[i];
  61729. var name_1 = fileToLoad.name.toLowerCase();
  61730. var entry = void 0;
  61731. fileToLoad.correctName = name_1;
  61732. if (items) {
  61733. var item = items[i];
  61734. if (item.getAsEntry) {
  61735. entry = item.getAsEntry();
  61736. }
  61737. else if (item.webkitGetAsEntry) {
  61738. entry = item.webkitGetAsEntry();
  61739. }
  61740. }
  61741. if (!entry) {
  61742. files_1.push(fileToLoad);
  61743. }
  61744. else {
  61745. if (entry.isDirectory) {
  61746. folders.push(entry);
  61747. }
  61748. else {
  61749. files_1.push(fileToLoad);
  61750. }
  61751. }
  61752. }
  61753. if (folders.length === 0) {
  61754. this._processFiles(files_1);
  61755. this._processReload();
  61756. }
  61757. else {
  61758. var remaining = { count: folders.length };
  61759. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61760. var folder = folders_1[_i];
  61761. this._traverseFolder(folder, files_1, remaining, function () {
  61762. _this._processFiles(files_1);
  61763. if (remaining.count === 0) {
  61764. _this._processReload();
  61765. }
  61766. });
  61767. }
  61768. }
  61769. }
  61770. };
  61771. FilesInput.prototype._processReload = function () {
  61772. if (this._onReloadCallback) {
  61773. this._onReloadCallback(this._sceneFileToLoad);
  61774. }
  61775. else {
  61776. this.reload();
  61777. }
  61778. };
  61779. FilesInput.prototype.reload = function () {
  61780. var _this = this;
  61781. // If a scene file has been provided
  61782. if (this._sceneFileToLoad) {
  61783. if (this._currentScene) {
  61784. if (BABYLON.Tools.errorsCount > 0) {
  61785. BABYLON.Tools.ClearLogCache();
  61786. }
  61787. this._engine.stopRenderLoop();
  61788. this._currentScene.dispose();
  61789. }
  61790. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61791. if (_this._progressCallback) {
  61792. _this._progressCallback(progress);
  61793. }
  61794. }).then(function (scene) {
  61795. _this._currentScene = scene;
  61796. if (_this._sceneLoadedCallback) {
  61797. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61798. }
  61799. // Wait for textures and shaders to be ready
  61800. _this._currentScene.executeWhenReady(function () {
  61801. _this._engine.runRenderLoop(function () {
  61802. _this.renderFunction();
  61803. });
  61804. });
  61805. }).catch(function (error) {
  61806. if (_this._errorCallback) {
  61807. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61808. }
  61809. });
  61810. }
  61811. else {
  61812. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61813. }
  61814. };
  61815. FilesInput.FilesToLoad = {};
  61816. return FilesInput;
  61817. }());
  61818. BABYLON.FilesInput = FilesInput;
  61819. })(BABYLON || (BABYLON = {}));
  61820. //# sourceMappingURL=babylon.filesInput.js.map
  61821. var BABYLON;
  61822. (function (BABYLON) {
  61823. /**
  61824. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61825. * The underlying implementation relies on an associative array to ensure the best performances.
  61826. * The value can be anything including 'null' but except 'undefined'
  61827. */
  61828. var StringDictionary = /** @class */ (function () {
  61829. function StringDictionary() {
  61830. this._count = 0;
  61831. this._data = {};
  61832. }
  61833. /**
  61834. * This will clear this dictionary and copy the content from the 'source' one.
  61835. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61836. * @param source the dictionary to take the content from and copy to this dictionary
  61837. */
  61838. StringDictionary.prototype.copyFrom = function (source) {
  61839. var _this = this;
  61840. this.clear();
  61841. source.forEach(function (t, v) { return _this.add(t, v); });
  61842. };
  61843. /**
  61844. * Get a value based from its key
  61845. * @param key the given key to get the matching value from
  61846. * @return the value if found, otherwise undefined is returned
  61847. */
  61848. StringDictionary.prototype.get = function (key) {
  61849. var val = this._data[key];
  61850. if (val !== undefined) {
  61851. return val;
  61852. }
  61853. return undefined;
  61854. };
  61855. /**
  61856. * Get a value from its key or add it if it doesn't exist.
  61857. * This method will ensure you that a given key/data will be present in the dictionary.
  61858. * @param key the given key to get the matching value from
  61859. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61860. * The factory will only be invoked if there's no data for the given key.
  61861. * @return the value corresponding to the key.
  61862. */
  61863. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61864. var val = this.get(key);
  61865. if (val !== undefined) {
  61866. return val;
  61867. }
  61868. val = factory(key);
  61869. if (val) {
  61870. this.add(key, val);
  61871. }
  61872. return val;
  61873. };
  61874. /**
  61875. * Get a value from its key if present in the dictionary otherwise add it
  61876. * @param key the key to get the value from
  61877. * @param val if there's no such key/value pair in the dictionary add it with this value
  61878. * @return the value corresponding to the key
  61879. */
  61880. StringDictionary.prototype.getOrAdd = function (key, val) {
  61881. var curVal = this.get(key);
  61882. if (curVal !== undefined) {
  61883. return curVal;
  61884. }
  61885. this.add(key, val);
  61886. return val;
  61887. };
  61888. /**
  61889. * Check if there's a given key in the dictionary
  61890. * @param key the key to check for
  61891. * @return true if the key is present, false otherwise
  61892. */
  61893. StringDictionary.prototype.contains = function (key) {
  61894. return this._data[key] !== undefined;
  61895. };
  61896. /**
  61897. * Add a new key and its corresponding value
  61898. * @param key the key to add
  61899. * @param value the value corresponding to the key
  61900. * @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
  61901. */
  61902. StringDictionary.prototype.add = function (key, value) {
  61903. if (this._data[key] !== undefined) {
  61904. return false;
  61905. }
  61906. this._data[key] = value;
  61907. ++this._count;
  61908. return true;
  61909. };
  61910. StringDictionary.prototype.set = function (key, value) {
  61911. if (this._data[key] === undefined) {
  61912. return false;
  61913. }
  61914. this._data[key] = value;
  61915. return true;
  61916. };
  61917. /**
  61918. * Get the element of the given key and remove it from the dictionary
  61919. * @param key
  61920. */
  61921. StringDictionary.prototype.getAndRemove = function (key) {
  61922. var val = this.get(key);
  61923. if (val !== undefined) {
  61924. delete this._data[key];
  61925. --this._count;
  61926. return val;
  61927. }
  61928. return null;
  61929. };
  61930. /**
  61931. * Remove a key/value from the dictionary.
  61932. * @param key the key to remove
  61933. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61934. */
  61935. StringDictionary.prototype.remove = function (key) {
  61936. if (this.contains(key)) {
  61937. delete this._data[key];
  61938. --this._count;
  61939. return true;
  61940. }
  61941. return false;
  61942. };
  61943. /**
  61944. * Clear the whole content of the dictionary
  61945. */
  61946. StringDictionary.prototype.clear = function () {
  61947. this._data = {};
  61948. this._count = 0;
  61949. };
  61950. Object.defineProperty(StringDictionary.prototype, "count", {
  61951. get: function () {
  61952. return this._count;
  61953. },
  61954. enumerable: true,
  61955. configurable: true
  61956. });
  61957. /**
  61958. * Execute a callback on each key/val of the dictionary.
  61959. * Note that you can remove any element in this dictionary in the callback implementation
  61960. * @param callback the callback to execute on a given key/value pair
  61961. */
  61962. StringDictionary.prototype.forEach = function (callback) {
  61963. for (var cur in this._data) {
  61964. var val = this._data[cur];
  61965. callback(cur, val);
  61966. }
  61967. };
  61968. /**
  61969. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61970. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61971. * Note that you can remove any element in this dictionary in the callback implementation
  61972. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61973. */
  61974. StringDictionary.prototype.first = function (callback) {
  61975. for (var cur in this._data) {
  61976. var val = this._data[cur];
  61977. var res = callback(cur, val);
  61978. if (res) {
  61979. return res;
  61980. }
  61981. }
  61982. return null;
  61983. };
  61984. return StringDictionary;
  61985. }());
  61986. BABYLON.StringDictionary = StringDictionary;
  61987. })(BABYLON || (BABYLON = {}));
  61988. //# sourceMappingURL=babylon.stringDictionary.js.map
  61989. var BABYLON;
  61990. (function (BABYLON) {
  61991. var Tags = /** @class */ (function () {
  61992. function Tags() {
  61993. }
  61994. Tags.EnableFor = function (obj) {
  61995. obj._tags = obj._tags || {};
  61996. obj.hasTags = function () {
  61997. return Tags.HasTags(obj);
  61998. };
  61999. obj.addTags = function (tagsString) {
  62000. return Tags.AddTagsTo(obj, tagsString);
  62001. };
  62002. obj.removeTags = function (tagsString) {
  62003. return Tags.RemoveTagsFrom(obj, tagsString);
  62004. };
  62005. obj.matchesTagsQuery = function (tagsQuery) {
  62006. return Tags.MatchesQuery(obj, tagsQuery);
  62007. };
  62008. };
  62009. Tags.DisableFor = function (obj) {
  62010. delete obj._tags;
  62011. delete obj.hasTags;
  62012. delete obj.addTags;
  62013. delete obj.removeTags;
  62014. delete obj.matchesTagsQuery;
  62015. };
  62016. Tags.HasTags = function (obj) {
  62017. if (!obj._tags) {
  62018. return false;
  62019. }
  62020. return !BABYLON.Tools.IsEmpty(obj._tags);
  62021. };
  62022. Tags.GetTags = function (obj, asString) {
  62023. if (asString === void 0) { asString = true; }
  62024. if (!obj._tags) {
  62025. return null;
  62026. }
  62027. if (asString) {
  62028. var tagsArray = [];
  62029. for (var tag in obj._tags) {
  62030. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62031. tagsArray.push(tag);
  62032. }
  62033. }
  62034. return tagsArray.join(" ");
  62035. }
  62036. else {
  62037. return obj._tags;
  62038. }
  62039. };
  62040. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62041. // a tag cannot start with '||', '&&', and '!'
  62042. // it cannot contain whitespaces
  62043. Tags.AddTagsTo = function (obj, tagsString) {
  62044. if (!tagsString) {
  62045. return;
  62046. }
  62047. if (typeof tagsString !== "string") {
  62048. return;
  62049. }
  62050. var tags = tagsString.split(" ");
  62051. tags.forEach(function (tag, index, array) {
  62052. Tags._AddTagTo(obj, tag);
  62053. });
  62054. };
  62055. Tags._AddTagTo = function (obj, tag) {
  62056. tag = tag.trim();
  62057. if (tag === "" || tag === "true" || tag === "false") {
  62058. return;
  62059. }
  62060. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62061. return;
  62062. }
  62063. Tags.EnableFor(obj);
  62064. obj._tags[tag] = true;
  62065. };
  62066. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62067. if (!Tags.HasTags(obj)) {
  62068. return;
  62069. }
  62070. var tags = tagsString.split(" ");
  62071. for (var t in tags) {
  62072. Tags._RemoveTagFrom(obj, tags[t]);
  62073. }
  62074. };
  62075. Tags._RemoveTagFrom = function (obj, tag) {
  62076. delete obj._tags[tag];
  62077. };
  62078. Tags.MatchesQuery = function (obj, tagsQuery) {
  62079. if (tagsQuery === undefined) {
  62080. return true;
  62081. }
  62082. if (tagsQuery === "") {
  62083. return Tags.HasTags(obj);
  62084. }
  62085. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62086. };
  62087. return Tags;
  62088. }());
  62089. BABYLON.Tags = Tags;
  62090. })(BABYLON || (BABYLON = {}));
  62091. //# sourceMappingURL=babylon.tags.js.map
  62092. var BABYLON;
  62093. (function (BABYLON) {
  62094. var AndOrNotEvaluator = /** @class */ (function () {
  62095. function AndOrNotEvaluator() {
  62096. }
  62097. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62098. if (!query.match(/\([^\(\)]*\)/g)) {
  62099. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62100. }
  62101. else {
  62102. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62103. // remove parenthesis
  62104. r = r.slice(1, r.length - 1);
  62105. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62106. });
  62107. }
  62108. if (query === "true") {
  62109. return true;
  62110. }
  62111. if (query === "false") {
  62112. return false;
  62113. }
  62114. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62115. };
  62116. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62117. evaluateCallback = evaluateCallback || (function (r) {
  62118. return r === "true" ? true : false;
  62119. });
  62120. var result;
  62121. var or = parenthesisContent.split("||");
  62122. for (var i in or) {
  62123. if (or.hasOwnProperty(i)) {
  62124. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62125. var and = ori.split("&&");
  62126. if (and.length > 1) {
  62127. for (var j = 0; j < and.length; ++j) {
  62128. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62129. if (andj !== "true" && andj !== "false") {
  62130. if (andj[0] === "!") {
  62131. result = !evaluateCallback(andj.substring(1));
  62132. }
  62133. else {
  62134. result = evaluateCallback(andj);
  62135. }
  62136. }
  62137. else {
  62138. result = andj === "true" ? true : false;
  62139. }
  62140. if (!result) {
  62141. ori = "false";
  62142. break;
  62143. }
  62144. }
  62145. }
  62146. if (result || ori === "true") {
  62147. result = true;
  62148. break;
  62149. }
  62150. // result equals false (or undefined)
  62151. if (ori !== "true" && ori !== "false") {
  62152. if (ori[0] === "!") {
  62153. result = !evaluateCallback(ori.substring(1));
  62154. }
  62155. else {
  62156. result = evaluateCallback(ori);
  62157. }
  62158. }
  62159. else {
  62160. result = ori === "true" ? true : false;
  62161. }
  62162. }
  62163. }
  62164. // the whole parenthesis scope is replaced by 'true' or 'false'
  62165. return result ? "true" : "false";
  62166. };
  62167. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62168. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62169. // remove whitespaces
  62170. r = r.replace(/[\s]/g, function () { return ""; });
  62171. return r.length % 2 ? "!" : "";
  62172. });
  62173. booleanString = booleanString.trim();
  62174. if (booleanString === "!true") {
  62175. booleanString = "false";
  62176. }
  62177. else if (booleanString === "!false") {
  62178. booleanString = "true";
  62179. }
  62180. return booleanString;
  62181. };
  62182. return AndOrNotEvaluator;
  62183. }());
  62184. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62185. })(BABYLON || (BABYLON = {}));
  62186. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62187. var BABYLON;
  62188. (function (BABYLON) {
  62189. var Database = /** @class */ (function () {
  62190. function Database(urlToScene, callbackManifestChecked) {
  62191. // Handling various flavors of prefixed version of IndexedDB
  62192. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62193. this.callbackManifestChecked = callbackManifestChecked;
  62194. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62195. this.db = null;
  62196. this._enableSceneOffline = false;
  62197. this._enableTexturesOffline = false;
  62198. this.manifestVersionFound = 0;
  62199. this.mustUpdateRessources = false;
  62200. this.hasReachedQuota = false;
  62201. if (!Database.IDBStorageEnabled) {
  62202. this.callbackManifestChecked(true);
  62203. }
  62204. else {
  62205. this.checkManifestFile();
  62206. }
  62207. }
  62208. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62209. get: function () {
  62210. return this._enableSceneOffline;
  62211. },
  62212. enumerable: true,
  62213. configurable: true
  62214. });
  62215. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62216. get: function () {
  62217. return this._enableTexturesOffline;
  62218. },
  62219. enumerable: true,
  62220. configurable: true
  62221. });
  62222. Database.prototype.checkManifestFile = function () {
  62223. var _this = this;
  62224. var noManifestFile = function () {
  62225. _this._enableSceneOffline = false;
  62226. _this._enableTexturesOffline = false;
  62227. _this.callbackManifestChecked(false);
  62228. };
  62229. var timeStampUsed = false;
  62230. var manifestURL = this.currentSceneUrl + ".manifest";
  62231. var xhr = new XMLHttpRequest();
  62232. if (navigator.onLine) {
  62233. // Adding a timestamp to by-pass browsers' cache
  62234. timeStampUsed = true;
  62235. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62236. }
  62237. xhr.open("GET", manifestURL, true);
  62238. xhr.addEventListener("load", function () {
  62239. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62240. try {
  62241. var manifestFile = JSON.parse(xhr.response);
  62242. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62243. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62244. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62245. _this.manifestVersionFound = manifestFile.version;
  62246. }
  62247. if (_this.callbackManifestChecked) {
  62248. _this.callbackManifestChecked(true);
  62249. }
  62250. }
  62251. catch (ex) {
  62252. noManifestFile();
  62253. }
  62254. }
  62255. else {
  62256. noManifestFile();
  62257. }
  62258. }, false);
  62259. xhr.addEventListener("error", function (event) {
  62260. if (timeStampUsed) {
  62261. timeStampUsed = false;
  62262. // Let's retry without the timeStamp
  62263. // It could fail when coupled with HTML5 Offline API
  62264. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62265. xhr.open("GET", retryManifestURL, true);
  62266. xhr.send();
  62267. }
  62268. else {
  62269. noManifestFile();
  62270. }
  62271. }, false);
  62272. try {
  62273. xhr.send();
  62274. }
  62275. catch (ex) {
  62276. BABYLON.Tools.Error("Error on XHR send request.");
  62277. this.callbackManifestChecked(false);
  62278. }
  62279. };
  62280. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62281. var _this = this;
  62282. var handleError = function () {
  62283. _this.isSupported = false;
  62284. if (errorCallback)
  62285. errorCallback();
  62286. };
  62287. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62288. // Your browser doesn't support IndexedDB
  62289. this.isSupported = false;
  62290. if (errorCallback)
  62291. errorCallback();
  62292. }
  62293. else {
  62294. // If the DB hasn't been opened or created yet
  62295. if (!this.db) {
  62296. this.hasReachedQuota = false;
  62297. this.isSupported = true;
  62298. var request = this.idbFactory.open("babylonjs", 1);
  62299. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62300. request.onerror = function (event) {
  62301. handleError();
  62302. };
  62303. // executes when a version change transaction cannot complete due to other active transactions
  62304. request.onblocked = function (event) {
  62305. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62306. handleError();
  62307. };
  62308. // DB has been opened successfully
  62309. request.onsuccess = function (event) {
  62310. _this.db = request.result;
  62311. successCallback();
  62312. };
  62313. // Initialization of the DB. Creating Scenes & Textures stores
  62314. request.onupgradeneeded = function (event) {
  62315. _this.db = (event.target).result;
  62316. if (_this.db) {
  62317. try {
  62318. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62319. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62320. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62321. }
  62322. catch (ex) {
  62323. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62324. handleError();
  62325. }
  62326. }
  62327. };
  62328. }
  62329. else {
  62330. if (successCallback)
  62331. successCallback();
  62332. }
  62333. }
  62334. };
  62335. Database.prototype.loadImageFromDB = function (url, image) {
  62336. var _this = this;
  62337. var completeURL = Database.ReturnFullUrlLocation(url);
  62338. var saveAndLoadImage = function () {
  62339. if (!_this.hasReachedQuota && _this.db !== null) {
  62340. // the texture is not yet in the DB, let's try to save it
  62341. _this._saveImageIntoDBAsync(completeURL, image);
  62342. }
  62343. else {
  62344. image.src = url;
  62345. }
  62346. };
  62347. if (!this.mustUpdateRessources) {
  62348. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62349. }
  62350. else {
  62351. saveAndLoadImage();
  62352. }
  62353. };
  62354. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62355. if (this.isSupported && this.db !== null) {
  62356. var texture;
  62357. var transaction = this.db.transaction(["textures"]);
  62358. transaction.onabort = function (event) {
  62359. image.src = url;
  62360. };
  62361. transaction.oncomplete = function (event) {
  62362. var blobTextureURL;
  62363. if (texture) {
  62364. var URL = window.URL || window.webkitURL;
  62365. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62366. image.onerror = function () {
  62367. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62368. image.src = url;
  62369. };
  62370. image.src = blobTextureURL;
  62371. }
  62372. else {
  62373. notInDBCallback();
  62374. }
  62375. };
  62376. var getRequest = transaction.objectStore("textures").get(url);
  62377. getRequest.onsuccess = function (event) {
  62378. texture = (event.target).result;
  62379. };
  62380. getRequest.onerror = function (event) {
  62381. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62382. image.src = url;
  62383. };
  62384. }
  62385. else {
  62386. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62387. image.src = url;
  62388. }
  62389. };
  62390. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62391. var _this = this;
  62392. if (this.isSupported) {
  62393. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62394. var generateBlobUrl = function () {
  62395. var blobTextureURL;
  62396. if (blob) {
  62397. var URL = window.URL || window.webkitURL;
  62398. try {
  62399. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62400. }
  62401. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62402. catch (ex) {
  62403. blobTextureURL = URL.createObjectURL(blob);
  62404. }
  62405. }
  62406. if (blobTextureURL) {
  62407. image.src = blobTextureURL;
  62408. }
  62409. };
  62410. if (Database.IsUASupportingBlobStorage) {
  62411. var xhr = new XMLHttpRequest(), blob;
  62412. xhr.open("GET", url, true);
  62413. xhr.responseType = "blob";
  62414. xhr.addEventListener("load", function () {
  62415. if (xhr.status === 200 && _this.db) {
  62416. // Blob as response (XHR2)
  62417. blob = xhr.response;
  62418. var transaction = _this.db.transaction(["textures"], "readwrite");
  62419. // the transaction could abort because of a QuotaExceededError error
  62420. transaction.onabort = function (event) {
  62421. try {
  62422. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62423. var srcElement = (event.srcElement || event.target);
  62424. var error = srcElement.error;
  62425. if (error && error.name === "QuotaExceededError") {
  62426. _this.hasReachedQuota = true;
  62427. }
  62428. }
  62429. catch (ex) { }
  62430. generateBlobUrl();
  62431. };
  62432. transaction.oncomplete = function (event) {
  62433. generateBlobUrl();
  62434. };
  62435. var newTexture = { textureUrl: url, data: blob };
  62436. try {
  62437. // Put the blob into the dabase
  62438. var addRequest = transaction.objectStore("textures").put(newTexture);
  62439. addRequest.onsuccess = function (event) {
  62440. };
  62441. addRequest.onerror = function (event) {
  62442. generateBlobUrl();
  62443. };
  62444. }
  62445. catch (ex) {
  62446. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62447. if (ex.code === 25) {
  62448. Database.IsUASupportingBlobStorage = false;
  62449. }
  62450. image.src = url;
  62451. }
  62452. }
  62453. else {
  62454. image.src = url;
  62455. }
  62456. }, false);
  62457. xhr.addEventListener("error", function (event) {
  62458. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62459. image.src = url;
  62460. }, false);
  62461. xhr.send();
  62462. }
  62463. else {
  62464. image.src = url;
  62465. }
  62466. }
  62467. else {
  62468. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62469. image.src = url;
  62470. }
  62471. };
  62472. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62473. var _this = this;
  62474. var updateVersion = function () {
  62475. // the version is not yet in the DB or we need to update it
  62476. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62477. };
  62478. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62479. };
  62480. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62481. var _this = this;
  62482. if (this.isSupported && this.db) {
  62483. var version;
  62484. try {
  62485. var transaction = this.db.transaction(["versions"]);
  62486. transaction.oncomplete = function (event) {
  62487. if (version) {
  62488. // If the version in the JSON file is > than the version in DB
  62489. if (_this.manifestVersionFound > version.data) {
  62490. _this.mustUpdateRessources = true;
  62491. updateInDBCallback();
  62492. }
  62493. else {
  62494. callback(version.data);
  62495. }
  62496. }
  62497. else {
  62498. _this.mustUpdateRessources = true;
  62499. updateInDBCallback();
  62500. }
  62501. };
  62502. transaction.onabort = function (event) {
  62503. callback(-1);
  62504. };
  62505. var getRequest = transaction.objectStore("versions").get(url);
  62506. getRequest.onsuccess = function (event) {
  62507. version = (event.target).result;
  62508. };
  62509. getRequest.onerror = function (event) {
  62510. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62511. callback(-1);
  62512. };
  62513. }
  62514. catch (ex) {
  62515. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62516. callback(-1);
  62517. }
  62518. }
  62519. else {
  62520. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62521. callback(-1);
  62522. }
  62523. };
  62524. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62525. var _this = this;
  62526. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62527. try {
  62528. // Open a transaction to the database
  62529. var transaction = this.db.transaction(["versions"], "readwrite");
  62530. // the transaction could abort because of a QuotaExceededError error
  62531. transaction.onabort = function (event) {
  62532. try {
  62533. var error = event.srcElement['error'];
  62534. if (error && error.name === "QuotaExceededError") {
  62535. _this.hasReachedQuota = true;
  62536. }
  62537. }
  62538. catch (ex) { }
  62539. callback(-1);
  62540. };
  62541. transaction.oncomplete = function (event) {
  62542. callback(_this.manifestVersionFound);
  62543. };
  62544. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62545. // Put the scene into the database
  62546. var addRequest = transaction.objectStore("versions").put(newVersion);
  62547. addRequest.onsuccess = function (event) {
  62548. };
  62549. addRequest.onerror = function (event) {
  62550. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62551. };
  62552. }
  62553. catch (ex) {
  62554. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62555. callback(-1);
  62556. }
  62557. }
  62558. else {
  62559. callback(-1);
  62560. }
  62561. };
  62562. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62563. var _this = this;
  62564. var completeUrl = Database.ReturnFullUrlLocation(url);
  62565. var saveAndLoadFile = function () {
  62566. // the scene is not yet in the DB, let's try to save it
  62567. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62568. };
  62569. this._checkVersionFromDB(completeUrl, function (version) {
  62570. if (version !== -1) {
  62571. if (!_this.mustUpdateRessources) {
  62572. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62573. }
  62574. else {
  62575. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62576. }
  62577. }
  62578. else {
  62579. if (errorCallback) {
  62580. errorCallback();
  62581. }
  62582. }
  62583. });
  62584. };
  62585. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62586. if (this.isSupported && this.db) {
  62587. var targetStore;
  62588. if (url.indexOf(".babylon") !== -1) {
  62589. targetStore = "scenes";
  62590. }
  62591. else {
  62592. targetStore = "textures";
  62593. }
  62594. var file;
  62595. var transaction = this.db.transaction([targetStore]);
  62596. transaction.oncomplete = function (event) {
  62597. if (file) {
  62598. callback(file.data);
  62599. }
  62600. else {
  62601. notInDBCallback();
  62602. }
  62603. };
  62604. transaction.onabort = function (event) {
  62605. notInDBCallback();
  62606. };
  62607. var getRequest = transaction.objectStore(targetStore).get(url);
  62608. getRequest.onsuccess = function (event) {
  62609. file = (event.target).result;
  62610. };
  62611. getRequest.onerror = function (event) {
  62612. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62613. notInDBCallback();
  62614. };
  62615. }
  62616. else {
  62617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62618. callback();
  62619. }
  62620. };
  62621. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62622. var _this = this;
  62623. if (this.isSupported) {
  62624. var targetStore;
  62625. if (url.indexOf(".babylon") !== -1) {
  62626. targetStore = "scenes";
  62627. }
  62628. else {
  62629. targetStore = "textures";
  62630. }
  62631. // Create XHR
  62632. var xhr = new XMLHttpRequest();
  62633. var fileData;
  62634. xhr.open("GET", url, true);
  62635. if (useArrayBuffer) {
  62636. xhr.responseType = "arraybuffer";
  62637. }
  62638. if (progressCallback) {
  62639. xhr.onprogress = progressCallback;
  62640. }
  62641. xhr.addEventListener("load", function () {
  62642. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62643. // Blob as response (XHR2)
  62644. //fileData = xhr.responseText;
  62645. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62646. if (!_this.hasReachedQuota && _this.db) {
  62647. // Open a transaction to the database
  62648. var transaction = _this.db.transaction([targetStore], "readwrite");
  62649. // the transaction could abort because of a QuotaExceededError error
  62650. transaction.onabort = function (event) {
  62651. try {
  62652. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62653. var error = event.srcElement['error'];
  62654. if (error && error.name === "QuotaExceededError") {
  62655. _this.hasReachedQuota = true;
  62656. }
  62657. }
  62658. catch (ex) { }
  62659. callback(fileData);
  62660. };
  62661. transaction.oncomplete = function (event) {
  62662. callback(fileData);
  62663. };
  62664. var newFile;
  62665. if (targetStore === "scenes") {
  62666. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62667. }
  62668. else {
  62669. newFile = { textureUrl: url, data: fileData };
  62670. }
  62671. try {
  62672. // Put the scene into the database
  62673. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62674. addRequest.onsuccess = function (event) {
  62675. };
  62676. addRequest.onerror = function (event) {
  62677. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62678. };
  62679. }
  62680. catch (ex) {
  62681. callback(fileData);
  62682. }
  62683. }
  62684. else {
  62685. callback(fileData);
  62686. }
  62687. }
  62688. else {
  62689. callback();
  62690. }
  62691. }, false);
  62692. xhr.addEventListener("error", function (event) {
  62693. BABYLON.Tools.Error("error on XHR request.");
  62694. callback();
  62695. }, false);
  62696. xhr.send();
  62697. }
  62698. else {
  62699. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62700. callback();
  62701. }
  62702. };
  62703. Database.IsUASupportingBlobStorage = true;
  62704. Database.IDBStorageEnabled = true;
  62705. Database.parseURL = function (url) {
  62706. var a = document.createElement('a');
  62707. a.href = url;
  62708. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62709. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62710. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62711. return absLocation;
  62712. };
  62713. Database.ReturnFullUrlLocation = function (url) {
  62714. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62715. return (Database.parseURL(window.location.href) + url);
  62716. }
  62717. else {
  62718. return url;
  62719. }
  62720. };
  62721. return Database;
  62722. }());
  62723. BABYLON.Database = Database;
  62724. })(BABYLON || (BABYLON = {}));
  62725. //# sourceMappingURL=babylon.database.js.map
  62726. var BABYLON;
  62727. (function (BABYLON) {
  62728. var FresnelParameters = /** @class */ (function () {
  62729. function FresnelParameters() {
  62730. this._isEnabled = true;
  62731. this.leftColor = BABYLON.Color3.White();
  62732. this.rightColor = BABYLON.Color3.Black();
  62733. this.bias = 0;
  62734. this.power = 1;
  62735. }
  62736. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62737. get: function () {
  62738. return this._isEnabled;
  62739. },
  62740. set: function (value) {
  62741. if (this._isEnabled === value) {
  62742. return;
  62743. }
  62744. this._isEnabled = value;
  62745. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62746. },
  62747. enumerable: true,
  62748. configurable: true
  62749. });
  62750. FresnelParameters.prototype.clone = function () {
  62751. var newFresnelParameters = new FresnelParameters();
  62752. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62753. return newFresnelParameters;
  62754. };
  62755. FresnelParameters.prototype.serialize = function () {
  62756. var serializationObject = {};
  62757. serializationObject.isEnabled = this.isEnabled;
  62758. serializationObject.leftColor = this.leftColor;
  62759. serializationObject.rightColor = this.rightColor;
  62760. serializationObject.bias = this.bias;
  62761. serializationObject.power = this.power;
  62762. return serializationObject;
  62763. };
  62764. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62765. var fresnelParameters = new FresnelParameters();
  62766. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62767. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62768. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62769. fresnelParameters.bias = parsedFresnelParameters.bias;
  62770. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62771. return fresnelParameters;
  62772. };
  62773. return FresnelParameters;
  62774. }());
  62775. BABYLON.FresnelParameters = FresnelParameters;
  62776. })(BABYLON || (BABYLON = {}));
  62777. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62778. var BABYLON;
  62779. (function (BABYLON) {
  62780. var MultiMaterial = /** @class */ (function (_super) {
  62781. __extends(MultiMaterial, _super);
  62782. function MultiMaterial(name, scene) {
  62783. var _this = _super.call(this, name, scene, true) || this;
  62784. scene.multiMaterials.push(_this);
  62785. _this.subMaterials = new Array();
  62786. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62787. return _this;
  62788. }
  62789. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62790. get: function () {
  62791. return this._subMaterials;
  62792. },
  62793. set: function (value) {
  62794. this._subMaterials = value;
  62795. this._hookArray(value);
  62796. },
  62797. enumerable: true,
  62798. configurable: true
  62799. });
  62800. MultiMaterial.prototype._hookArray = function (array) {
  62801. var _this = this;
  62802. var oldPush = array.push;
  62803. array.push = function () {
  62804. var items = [];
  62805. for (var _i = 0; _i < arguments.length; _i++) {
  62806. items[_i] = arguments[_i];
  62807. }
  62808. var result = oldPush.apply(array, items);
  62809. _this._markAllSubMeshesAsTexturesDirty();
  62810. return result;
  62811. };
  62812. var oldSplice = array.splice;
  62813. array.splice = function (index, deleteCount) {
  62814. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62815. _this._markAllSubMeshesAsTexturesDirty();
  62816. return deleted;
  62817. };
  62818. };
  62819. // Properties
  62820. MultiMaterial.prototype.getSubMaterial = function (index) {
  62821. if (index < 0 || index >= this.subMaterials.length) {
  62822. return this.getScene().defaultMaterial;
  62823. }
  62824. return this.subMaterials[index];
  62825. };
  62826. MultiMaterial.prototype.getActiveTextures = function () {
  62827. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62828. if (subMaterial) {
  62829. return subMaterial.getActiveTextures();
  62830. }
  62831. else {
  62832. return [];
  62833. }
  62834. }));
  62835. var _a;
  62836. };
  62837. // Methods
  62838. MultiMaterial.prototype.getClassName = function () {
  62839. return "MultiMaterial";
  62840. };
  62841. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62842. for (var index = 0; index < this.subMaterials.length; index++) {
  62843. var subMaterial = this.subMaterials[index];
  62844. if (subMaterial) {
  62845. if (subMaterial.storeEffectOnSubMeshes) {
  62846. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62847. return false;
  62848. }
  62849. continue;
  62850. }
  62851. if (!subMaterial.isReady(mesh)) {
  62852. return false;
  62853. }
  62854. }
  62855. }
  62856. return true;
  62857. };
  62858. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62859. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62860. for (var index = 0; index < this.subMaterials.length; index++) {
  62861. var subMaterial = null;
  62862. var current = this.subMaterials[index];
  62863. if (cloneChildren && current) {
  62864. subMaterial = current.clone(name + "-" + current.name);
  62865. }
  62866. else {
  62867. subMaterial = this.subMaterials[index];
  62868. }
  62869. newMultiMaterial.subMaterials.push(subMaterial);
  62870. }
  62871. return newMultiMaterial;
  62872. };
  62873. MultiMaterial.prototype.serialize = function () {
  62874. var serializationObject = {};
  62875. serializationObject.name = this.name;
  62876. serializationObject.id = this.id;
  62877. if (BABYLON.Tags) {
  62878. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62879. }
  62880. serializationObject.materials = [];
  62881. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62882. var subMat = this.subMaterials[matIndex];
  62883. if (subMat) {
  62884. serializationObject.materials.push(subMat.id);
  62885. }
  62886. else {
  62887. serializationObject.materials.push(null);
  62888. }
  62889. }
  62890. return serializationObject;
  62891. };
  62892. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62893. var scene = this.getScene();
  62894. if (!scene) {
  62895. return;
  62896. }
  62897. var index = scene.multiMaterials.indexOf(this);
  62898. if (index >= 0) {
  62899. scene.multiMaterials.splice(index, 1);
  62900. }
  62901. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62902. };
  62903. return MultiMaterial;
  62904. }(BABYLON.Material));
  62905. BABYLON.MultiMaterial = MultiMaterial;
  62906. })(BABYLON || (BABYLON = {}));
  62907. //# sourceMappingURL=babylon.multiMaterial.js.map
  62908. var BABYLON;
  62909. (function (BABYLON) {
  62910. var FreeCameraTouchInput = /** @class */ (function () {
  62911. function FreeCameraTouchInput() {
  62912. this._offsetX = null;
  62913. this._offsetY = null;
  62914. this._pointerPressed = new Array();
  62915. this.touchAngularSensibility = 200000.0;
  62916. this.touchMoveSensibility = 250.0;
  62917. }
  62918. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62919. var _this = this;
  62920. var previousPosition = null;
  62921. if (this._pointerInput === undefined) {
  62922. this._onLostFocus = function (evt) {
  62923. _this._offsetX = null;
  62924. _this._offsetY = null;
  62925. };
  62926. this._pointerInput = function (p, s) {
  62927. var evt = p.event;
  62928. if (evt.pointerType === "mouse") {
  62929. return;
  62930. }
  62931. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62932. if (!noPreventDefault) {
  62933. evt.preventDefault();
  62934. }
  62935. _this._pointerPressed.push(evt.pointerId);
  62936. if (_this._pointerPressed.length !== 1) {
  62937. return;
  62938. }
  62939. previousPosition = {
  62940. x: evt.clientX,
  62941. y: evt.clientY
  62942. };
  62943. }
  62944. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62945. if (!noPreventDefault) {
  62946. evt.preventDefault();
  62947. }
  62948. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62949. if (index === -1) {
  62950. return;
  62951. }
  62952. _this._pointerPressed.splice(index, 1);
  62953. if (index != 0) {
  62954. return;
  62955. }
  62956. previousPosition = null;
  62957. _this._offsetX = null;
  62958. _this._offsetY = null;
  62959. }
  62960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62961. if (!noPreventDefault) {
  62962. evt.preventDefault();
  62963. }
  62964. if (!previousPosition) {
  62965. return;
  62966. }
  62967. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62968. if (index != 0) {
  62969. return;
  62970. }
  62971. _this._offsetX = evt.clientX - previousPosition.x;
  62972. _this._offsetY = -(evt.clientY - previousPosition.y);
  62973. }
  62974. };
  62975. }
  62976. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62977. if (this._onLostFocus) {
  62978. element.addEventListener("blur", this._onLostFocus);
  62979. }
  62980. };
  62981. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62982. if (this._pointerInput && element) {
  62983. if (this._observer) {
  62984. this.camera.getScene().onPointerObservable.remove(this._observer);
  62985. this._observer = null;
  62986. }
  62987. if (this._onLostFocus) {
  62988. element.removeEventListener("blur", this._onLostFocus);
  62989. this._onLostFocus = null;
  62990. }
  62991. this._pointerPressed = [];
  62992. this._offsetX = null;
  62993. this._offsetY = null;
  62994. }
  62995. };
  62996. FreeCameraTouchInput.prototype.checkInputs = function () {
  62997. if (this._offsetX && this._offsetY) {
  62998. var camera = this.camera;
  62999. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63000. if (this._pointerPressed.length > 1) {
  63001. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63002. }
  63003. else {
  63004. var speed = camera._computeLocalCameraSpeed();
  63005. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63006. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63007. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63008. }
  63009. }
  63010. };
  63011. FreeCameraTouchInput.prototype.getClassName = function () {
  63012. return "FreeCameraTouchInput";
  63013. };
  63014. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63015. return "touch";
  63016. };
  63017. __decorate([
  63018. BABYLON.serialize()
  63019. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63020. __decorate([
  63021. BABYLON.serialize()
  63022. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63023. return FreeCameraTouchInput;
  63024. }());
  63025. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63026. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63027. })(BABYLON || (BABYLON = {}));
  63028. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63029. var BABYLON;
  63030. (function (BABYLON) {
  63031. // We're mainly based on the logic defined into the FreeCamera code
  63032. var TouchCamera = /** @class */ (function (_super) {
  63033. __extends(TouchCamera, _super);
  63034. //-- end properties for backward compatibility for inputs
  63035. function TouchCamera(name, position, scene) {
  63036. var _this = _super.call(this, name, position, scene) || this;
  63037. _this.inputs.addTouch();
  63038. _this._setupInputs();
  63039. return _this;
  63040. }
  63041. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63042. //-- Begin properties for backward compatibility for inputs
  63043. get: function () {
  63044. var touch = this.inputs.attached["touch"];
  63045. if (touch)
  63046. return touch.touchAngularSensibility;
  63047. return 0;
  63048. },
  63049. set: function (value) {
  63050. var touch = this.inputs.attached["touch"];
  63051. if (touch)
  63052. touch.touchAngularSensibility = value;
  63053. },
  63054. enumerable: true,
  63055. configurable: true
  63056. });
  63057. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63058. get: function () {
  63059. var touch = this.inputs.attached["touch"];
  63060. if (touch)
  63061. return touch.touchMoveSensibility;
  63062. return 0;
  63063. },
  63064. set: function (value) {
  63065. var touch = this.inputs.attached["touch"];
  63066. if (touch)
  63067. touch.touchMoveSensibility = value;
  63068. },
  63069. enumerable: true,
  63070. configurable: true
  63071. });
  63072. TouchCamera.prototype.getClassName = function () {
  63073. return "TouchCamera";
  63074. };
  63075. TouchCamera.prototype._setupInputs = function () {
  63076. var mouse = this.inputs.attached["mouse"];
  63077. if (mouse) {
  63078. mouse.touchEnabled = false;
  63079. }
  63080. };
  63081. return TouchCamera;
  63082. }(BABYLON.FreeCamera));
  63083. BABYLON.TouchCamera = TouchCamera;
  63084. })(BABYLON || (BABYLON = {}));
  63085. //# sourceMappingURL=babylon.touchCamera.js.map
  63086. var BABYLON;
  63087. (function (BABYLON) {
  63088. var ProceduralTexture = /** @class */ (function (_super) {
  63089. __extends(ProceduralTexture, _super);
  63090. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63091. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63092. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63093. if (isCube === void 0) { isCube = false; }
  63094. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63095. _this.isCube = isCube;
  63096. _this.isEnabled = true;
  63097. _this._currentRefreshId = -1;
  63098. _this._refreshRate = 1;
  63099. _this._vertexBuffers = {};
  63100. _this._uniforms = new Array();
  63101. _this._samplers = new Array();
  63102. _this._textures = {};
  63103. _this._floats = {};
  63104. _this._floatsArrays = {};
  63105. _this._colors3 = {};
  63106. _this._colors4 = {};
  63107. _this._vectors2 = {};
  63108. _this._vectors3 = {};
  63109. _this._matrices = {};
  63110. _this._fallbackTextureUsed = false;
  63111. scene._proceduralTextures.push(_this);
  63112. _this._engine = scene.getEngine();
  63113. _this.name = name;
  63114. _this.isRenderTarget = true;
  63115. _this._size = size;
  63116. _this._generateMipMaps = generateMipMaps;
  63117. _this.setFragment(fragment);
  63118. _this._fallbackTexture = fallbackTexture;
  63119. if (isCube) {
  63120. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63121. _this.setFloat("face", 0);
  63122. }
  63123. else {
  63124. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63125. }
  63126. // VBO
  63127. var vertices = [];
  63128. vertices.push(1, 1);
  63129. vertices.push(-1, 1);
  63130. vertices.push(-1, -1);
  63131. vertices.push(1, -1);
  63132. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63133. _this._createIndexBuffer();
  63134. return _this;
  63135. }
  63136. ProceduralTexture.prototype._createIndexBuffer = function () {
  63137. var engine = this._engine;
  63138. // Indices
  63139. var indices = [];
  63140. indices.push(0);
  63141. indices.push(1);
  63142. indices.push(2);
  63143. indices.push(0);
  63144. indices.push(2);
  63145. indices.push(3);
  63146. this._indexBuffer = engine.createIndexBuffer(indices);
  63147. };
  63148. ProceduralTexture.prototype._rebuild = function () {
  63149. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63150. if (vb) {
  63151. vb._rebuild();
  63152. }
  63153. this._createIndexBuffer();
  63154. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63155. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63156. }
  63157. };
  63158. ProceduralTexture.prototype.reset = function () {
  63159. if (this._effect === undefined) {
  63160. return;
  63161. }
  63162. var engine = this._engine;
  63163. engine._releaseEffect(this._effect);
  63164. };
  63165. ProceduralTexture.prototype.isReady = function () {
  63166. var _this = this;
  63167. var engine = this._engine;
  63168. var shaders;
  63169. if (!this._fragment) {
  63170. return false;
  63171. }
  63172. if (this._fallbackTextureUsed) {
  63173. return true;
  63174. }
  63175. if (this._fragment.fragmentElement !== undefined) {
  63176. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63177. }
  63178. else {
  63179. shaders = { vertex: "procedural", fragment: this._fragment };
  63180. }
  63181. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63182. _this.releaseInternalTexture();
  63183. if (_this._fallbackTexture) {
  63184. _this._texture = _this._fallbackTexture._texture;
  63185. if (_this._texture) {
  63186. _this._texture.incrementReferences();
  63187. }
  63188. }
  63189. _this._fallbackTextureUsed = true;
  63190. });
  63191. return this._effect.isReady();
  63192. };
  63193. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63194. this._currentRefreshId = -1;
  63195. };
  63196. ProceduralTexture.prototype.setFragment = function (fragment) {
  63197. this._fragment = fragment;
  63198. };
  63199. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63200. get: function () {
  63201. return this._refreshRate;
  63202. },
  63203. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63204. set: function (value) {
  63205. this._refreshRate = value;
  63206. this.resetRefreshCounter();
  63207. },
  63208. enumerable: true,
  63209. configurable: true
  63210. });
  63211. ProceduralTexture.prototype._shouldRender = function () {
  63212. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63213. return false;
  63214. }
  63215. if (this._fallbackTextureUsed) {
  63216. return false;
  63217. }
  63218. if (this._currentRefreshId === -1) {
  63219. this._currentRefreshId = 1;
  63220. return true;
  63221. }
  63222. if (this.refreshRate === this._currentRefreshId) {
  63223. this._currentRefreshId = 1;
  63224. return true;
  63225. }
  63226. this._currentRefreshId++;
  63227. return false;
  63228. };
  63229. ProceduralTexture.prototype.getRenderSize = function () {
  63230. return this._size;
  63231. };
  63232. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63233. if (this._fallbackTextureUsed) {
  63234. return;
  63235. }
  63236. this.releaseInternalTexture();
  63237. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63238. };
  63239. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63240. if (this._uniforms.indexOf(uniformName) === -1) {
  63241. this._uniforms.push(uniformName);
  63242. }
  63243. };
  63244. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63245. if (this._samplers.indexOf(name) === -1) {
  63246. this._samplers.push(name);
  63247. }
  63248. this._textures[name] = texture;
  63249. return this;
  63250. };
  63251. ProceduralTexture.prototype.setFloat = function (name, value) {
  63252. this._checkUniform(name);
  63253. this._floats[name] = value;
  63254. return this;
  63255. };
  63256. ProceduralTexture.prototype.setFloats = function (name, value) {
  63257. this._checkUniform(name);
  63258. this._floatsArrays[name] = value;
  63259. return this;
  63260. };
  63261. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63262. this._checkUniform(name);
  63263. this._colors3[name] = value;
  63264. return this;
  63265. };
  63266. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63267. this._checkUniform(name);
  63268. this._colors4[name] = value;
  63269. return this;
  63270. };
  63271. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63272. this._checkUniform(name);
  63273. this._vectors2[name] = value;
  63274. return this;
  63275. };
  63276. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63277. this._checkUniform(name);
  63278. this._vectors3[name] = value;
  63279. return this;
  63280. };
  63281. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63282. this._checkUniform(name);
  63283. this._matrices[name] = value;
  63284. return this;
  63285. };
  63286. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63287. var scene = this.getScene();
  63288. if (!scene) {
  63289. return;
  63290. }
  63291. var engine = this._engine;
  63292. // Render
  63293. engine.enableEffect(this._effect);
  63294. engine.setState(false);
  63295. // Texture
  63296. for (var name in this._textures) {
  63297. this._effect.setTexture(name, this._textures[name]);
  63298. }
  63299. // Float
  63300. for (name in this._floats) {
  63301. this._effect.setFloat(name, this._floats[name]);
  63302. }
  63303. // Floats
  63304. for (name in this._floatsArrays) {
  63305. this._effect.setArray(name, this._floatsArrays[name]);
  63306. }
  63307. // Color3
  63308. for (name in this._colors3) {
  63309. this._effect.setColor3(name, this._colors3[name]);
  63310. }
  63311. // Color4
  63312. for (name in this._colors4) {
  63313. var color = this._colors4[name];
  63314. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63315. }
  63316. // Vector2
  63317. for (name in this._vectors2) {
  63318. this._effect.setVector2(name, this._vectors2[name]);
  63319. }
  63320. // Vector3
  63321. for (name in this._vectors3) {
  63322. this._effect.setVector3(name, this._vectors3[name]);
  63323. }
  63324. // Matrix
  63325. for (name in this._matrices) {
  63326. this._effect.setMatrix(name, this._matrices[name]);
  63327. }
  63328. if (!this._texture) {
  63329. return;
  63330. }
  63331. if (this.isCube) {
  63332. for (var face = 0; face < 6; face++) {
  63333. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63334. // VBOs
  63335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63336. this._effect.setFloat("face", face);
  63337. // Clear
  63338. engine.clear(scene.clearColor, true, true, true);
  63339. // Draw order
  63340. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63341. // Mipmaps
  63342. if (face === 5) {
  63343. engine.generateMipMapsForCubemap(this._texture);
  63344. }
  63345. }
  63346. }
  63347. else {
  63348. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63349. // VBOs
  63350. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63351. // Clear
  63352. engine.clear(scene.clearColor, true, true, true);
  63353. // Draw order
  63354. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63355. }
  63356. // Unbind
  63357. engine.unBindFramebuffer(this._texture, this.isCube);
  63358. if (this.onGenerated) {
  63359. this.onGenerated();
  63360. }
  63361. };
  63362. ProceduralTexture.prototype.clone = function () {
  63363. var textureSize = this.getSize();
  63364. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63365. // Base texture
  63366. newTexture.hasAlpha = this.hasAlpha;
  63367. newTexture.level = this.level;
  63368. // RenderTarget Texture
  63369. newTexture.coordinatesMode = this.coordinatesMode;
  63370. return newTexture;
  63371. };
  63372. ProceduralTexture.prototype.dispose = function () {
  63373. var scene = this.getScene();
  63374. if (!scene) {
  63375. return;
  63376. }
  63377. var index = scene._proceduralTextures.indexOf(this);
  63378. if (index >= 0) {
  63379. scene._proceduralTextures.splice(index, 1);
  63380. }
  63381. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63382. if (vertexBuffer) {
  63383. vertexBuffer.dispose();
  63384. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63385. }
  63386. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63387. this._indexBuffer = null;
  63388. }
  63389. _super.prototype.dispose.call(this);
  63390. };
  63391. return ProceduralTexture;
  63392. }(BABYLON.Texture));
  63393. BABYLON.ProceduralTexture = ProceduralTexture;
  63394. })(BABYLON || (BABYLON = {}));
  63395. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63396. var BABYLON;
  63397. (function (BABYLON) {
  63398. var CustomProceduralTexture = /** @class */ (function (_super) {
  63399. __extends(CustomProceduralTexture, _super);
  63400. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63401. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63402. _this._animate = true;
  63403. _this._time = 0;
  63404. _this._texturePath = texturePath;
  63405. //Try to load json
  63406. _this.loadJson(texturePath);
  63407. _this.refreshRate = 1;
  63408. return _this;
  63409. }
  63410. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63411. var _this = this;
  63412. var noConfigFile = function () {
  63413. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63414. try {
  63415. _this.setFragment(_this._texturePath);
  63416. }
  63417. catch (ex) {
  63418. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63419. }
  63420. };
  63421. var configFileUrl = jsonUrl + "/config.json";
  63422. var xhr = new XMLHttpRequest();
  63423. xhr.open("GET", configFileUrl, true);
  63424. xhr.addEventListener("load", function () {
  63425. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63426. try {
  63427. _this._config = JSON.parse(xhr.response);
  63428. _this.updateShaderUniforms();
  63429. _this.updateTextures();
  63430. _this.setFragment(_this._texturePath + "/custom");
  63431. _this._animate = _this._config.animate;
  63432. _this.refreshRate = _this._config.refreshrate;
  63433. }
  63434. catch (ex) {
  63435. noConfigFile();
  63436. }
  63437. }
  63438. else {
  63439. noConfigFile();
  63440. }
  63441. }, false);
  63442. xhr.addEventListener("error", function () {
  63443. noConfigFile();
  63444. }, false);
  63445. try {
  63446. xhr.send();
  63447. }
  63448. catch (ex) {
  63449. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63450. }
  63451. };
  63452. CustomProceduralTexture.prototype.isReady = function () {
  63453. if (!_super.prototype.isReady.call(this)) {
  63454. return false;
  63455. }
  63456. for (var name in this._textures) {
  63457. var texture = this._textures[name];
  63458. if (!texture.isReady()) {
  63459. return false;
  63460. }
  63461. }
  63462. return true;
  63463. };
  63464. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63465. var scene = this.getScene();
  63466. if (this._animate && scene) {
  63467. this._time += scene.getAnimationRatio() * 0.03;
  63468. this.updateShaderUniforms();
  63469. }
  63470. _super.prototype.render.call(this, useCameraPostProcess);
  63471. };
  63472. CustomProceduralTexture.prototype.updateTextures = function () {
  63473. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63474. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63475. }
  63476. };
  63477. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63478. if (this._config) {
  63479. for (var j = 0; j < this._config.uniforms.length; j++) {
  63480. var uniform = this._config.uniforms[j];
  63481. switch (uniform.type) {
  63482. case "float":
  63483. this.setFloat(uniform.name, uniform.value);
  63484. break;
  63485. case "color3":
  63486. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63487. break;
  63488. case "color4":
  63489. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63490. break;
  63491. case "vector2":
  63492. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63493. break;
  63494. case "vector3":
  63495. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63496. break;
  63497. }
  63498. }
  63499. }
  63500. this.setFloat("time", this._time);
  63501. };
  63502. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63503. get: function () {
  63504. return this._animate;
  63505. },
  63506. set: function (value) {
  63507. this._animate = value;
  63508. },
  63509. enumerable: true,
  63510. configurable: true
  63511. });
  63512. return CustomProceduralTexture;
  63513. }(BABYLON.ProceduralTexture));
  63514. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63515. })(BABYLON || (BABYLON = {}));
  63516. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63517. var BABYLON;
  63518. (function (BABYLON) {
  63519. var FreeCameraGamepadInput = /** @class */ (function () {
  63520. function FreeCameraGamepadInput() {
  63521. this.gamepadAngularSensibility = 200;
  63522. this.gamepadMoveSensibility = 40;
  63523. // private members
  63524. this._cameraTransform = BABYLON.Matrix.Identity();
  63525. this._deltaTransform = BABYLON.Vector3.Zero();
  63526. this._vector3 = BABYLON.Vector3.Zero();
  63527. this._vector2 = BABYLON.Vector2.Zero();
  63528. }
  63529. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63530. var _this = this;
  63531. var manager = this.camera.getScene().gamepadManager;
  63532. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63533. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63534. // prioritize XBOX gamepads.
  63535. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63536. _this.gamepad = gamepad;
  63537. }
  63538. }
  63539. });
  63540. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63541. if (_this.gamepad === gamepad) {
  63542. _this.gamepad = null;
  63543. }
  63544. });
  63545. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63546. };
  63547. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63548. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63549. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63550. this.gamepad = null;
  63551. };
  63552. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63553. if (this.gamepad && this.gamepad.leftStick) {
  63554. var camera = this.camera;
  63555. var LSValues = this.gamepad.leftStick;
  63556. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63557. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63558. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63559. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63560. var RSValues = this.gamepad.rightStick;
  63561. if (RSValues) {
  63562. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63563. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63564. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63565. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63566. }
  63567. else {
  63568. RSValues = { x: 0, y: 0 };
  63569. }
  63570. if (!camera.rotationQuaternion) {
  63571. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63572. }
  63573. else {
  63574. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63575. }
  63576. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63577. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63578. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63579. camera.cameraDirection.addInPlace(this._deltaTransform);
  63580. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63581. camera.cameraRotation.addInPlace(this._vector2);
  63582. }
  63583. };
  63584. FreeCameraGamepadInput.prototype.getClassName = function () {
  63585. return "FreeCameraGamepadInput";
  63586. };
  63587. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63588. return "gamepad";
  63589. };
  63590. __decorate([
  63591. BABYLON.serialize()
  63592. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63593. __decorate([
  63594. BABYLON.serialize()
  63595. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63596. return FreeCameraGamepadInput;
  63597. }());
  63598. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63599. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63600. })(BABYLON || (BABYLON = {}));
  63601. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63602. var BABYLON;
  63603. (function (BABYLON) {
  63604. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63605. function ArcRotateCameraGamepadInput() {
  63606. this.gamepadRotationSensibility = 80;
  63607. this.gamepadMoveSensibility = 40;
  63608. }
  63609. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63610. var _this = this;
  63611. var manager = this.camera.getScene().gamepadManager;
  63612. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63613. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63614. // prioritize XBOX gamepads.
  63615. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63616. _this.gamepad = gamepad;
  63617. }
  63618. }
  63619. });
  63620. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63621. if (_this.gamepad === gamepad) {
  63622. _this.gamepad = null;
  63623. }
  63624. });
  63625. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63626. };
  63627. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63628. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63629. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63630. this.gamepad = null;
  63631. };
  63632. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63633. if (this.gamepad) {
  63634. var camera = this.camera;
  63635. var RSValues = this.gamepad.rightStick;
  63636. if (RSValues) {
  63637. if (RSValues.x != 0) {
  63638. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63639. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63640. camera.inertialAlphaOffset += normalizedRX;
  63641. }
  63642. }
  63643. if (RSValues.y != 0) {
  63644. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63645. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63646. camera.inertialBetaOffset += normalizedRY;
  63647. }
  63648. }
  63649. }
  63650. var LSValues = this.gamepad.leftStick;
  63651. if (LSValues && LSValues.y != 0) {
  63652. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63653. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63654. this.camera.inertialRadiusOffset -= normalizedLY;
  63655. }
  63656. }
  63657. }
  63658. };
  63659. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63660. return "ArcRotateCameraGamepadInput";
  63661. };
  63662. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63663. return "gamepad";
  63664. };
  63665. __decorate([
  63666. BABYLON.serialize()
  63667. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63668. __decorate([
  63669. BABYLON.serialize()
  63670. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63671. return ArcRotateCameraGamepadInput;
  63672. }());
  63673. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63674. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63675. })(BABYLON || (BABYLON = {}));
  63676. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63677. var BABYLON;
  63678. (function (BABYLON) {
  63679. var GamepadManager = /** @class */ (function () {
  63680. function GamepadManager(_scene) {
  63681. var _this = this;
  63682. this._scene = _scene;
  63683. this._babylonGamepads = [];
  63684. this._oneGamepadConnected = false;
  63685. this._isMonitoring = false;
  63686. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63687. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63688. this._gamepadEventSupported = false;
  63689. }
  63690. else {
  63691. this._gamepadEventSupported = 'GamepadEvent' in window;
  63692. this._gamepadSupport = (navigator.getGamepads ||
  63693. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63694. }
  63695. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63696. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63697. for (var i in _this._babylonGamepads) {
  63698. var gamepad = _this._babylonGamepads[i];
  63699. if (gamepad && gamepad._isConnected) {
  63700. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63701. }
  63702. }
  63703. });
  63704. this._onGamepadConnectedEvent = function (evt) {
  63705. var gamepad = evt.gamepad;
  63706. if (gamepad.index in _this._babylonGamepads) {
  63707. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63708. return;
  63709. }
  63710. }
  63711. var newGamepad;
  63712. if (_this._babylonGamepads[gamepad.index]) {
  63713. newGamepad = _this._babylonGamepads[gamepad.index];
  63714. newGamepad.browserGamepad = gamepad;
  63715. newGamepad._isConnected = true;
  63716. }
  63717. else {
  63718. newGamepad = _this._addNewGamepad(gamepad);
  63719. }
  63720. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63721. _this._startMonitoringGamepads();
  63722. };
  63723. this._onGamepadDisconnectedEvent = function (evt) {
  63724. var gamepad = evt.gamepad;
  63725. // Remove the gamepad from the list of gamepads to monitor.
  63726. for (var i in _this._babylonGamepads) {
  63727. if (_this._babylonGamepads[i].index === gamepad.index) {
  63728. var disconnectedGamepad = _this._babylonGamepads[i];
  63729. disconnectedGamepad._isConnected = false;
  63730. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63731. break;
  63732. }
  63733. }
  63734. };
  63735. if (this._gamepadSupport) {
  63736. //first add already-connected gamepads
  63737. this._updateGamepadObjects();
  63738. if (this._babylonGamepads.length) {
  63739. this._startMonitoringGamepads();
  63740. }
  63741. // Checking if the gamepad connected event is supported (like in Firefox)
  63742. if (this._gamepadEventSupported) {
  63743. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63744. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63745. }
  63746. else {
  63747. this._startMonitoringGamepads();
  63748. }
  63749. }
  63750. }
  63751. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63752. get: function () {
  63753. return this._babylonGamepads;
  63754. },
  63755. enumerable: true,
  63756. configurable: true
  63757. });
  63758. GamepadManager.prototype.getGamepadByType = function (type) {
  63759. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63760. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63761. var gamepad = _a[_i];
  63762. if (gamepad && gamepad.type === type) {
  63763. return gamepad;
  63764. }
  63765. }
  63766. return null;
  63767. };
  63768. GamepadManager.prototype.dispose = function () {
  63769. if (this._gamepadEventSupported) {
  63770. if (this._onGamepadConnectedEvent) {
  63771. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63772. }
  63773. if (this._onGamepadDisconnectedEvent) {
  63774. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63775. }
  63776. this._onGamepadConnectedEvent = null;
  63777. this._onGamepadDisconnectedEvent = null;
  63778. }
  63779. this._babylonGamepads.forEach(function (gamepad) {
  63780. gamepad.dispose();
  63781. });
  63782. this.onGamepadConnectedObservable.clear();
  63783. this.onGamepadDisconnectedObservable.clear();
  63784. this._oneGamepadConnected = false;
  63785. this._stopMonitoringGamepads();
  63786. this._babylonGamepads = [];
  63787. };
  63788. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63789. if (!this._oneGamepadConnected) {
  63790. this._oneGamepadConnected = true;
  63791. }
  63792. var newGamepad;
  63793. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63794. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63795. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63796. }
  63797. else if (gamepad.pose) {
  63798. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63799. }
  63800. else {
  63801. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63802. }
  63803. this._babylonGamepads[newGamepad.index] = newGamepad;
  63804. return newGamepad;
  63805. };
  63806. GamepadManager.prototype._startMonitoringGamepads = function () {
  63807. if (!this._isMonitoring) {
  63808. this._isMonitoring = true;
  63809. //back-comp
  63810. if (!this._scene) {
  63811. this._checkGamepadsStatus();
  63812. }
  63813. }
  63814. };
  63815. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63816. this._isMonitoring = false;
  63817. };
  63818. GamepadManager.prototype._checkGamepadsStatus = function () {
  63819. var _this = this;
  63820. // Hack to be compatible Chrome
  63821. this._updateGamepadObjects();
  63822. for (var i in this._babylonGamepads) {
  63823. var gamepad = this._babylonGamepads[i];
  63824. if (!gamepad || !gamepad.isConnected) {
  63825. continue;
  63826. }
  63827. gamepad.update();
  63828. }
  63829. if (this._isMonitoring && !this._scene) {
  63830. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63831. }
  63832. };
  63833. // This function is called only on Chrome, which does not properly support
  63834. // connection/disconnection events and forces you to recopy again the gamepad object
  63835. GamepadManager.prototype._updateGamepadObjects = function () {
  63836. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63837. for (var i = 0; i < gamepads.length; i++) {
  63838. if (gamepads[i]) {
  63839. if (!this._babylonGamepads[gamepads[i].index]) {
  63840. var newGamepad = this._addNewGamepad(gamepads[i]);
  63841. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63842. }
  63843. else {
  63844. // Forced to copy again this object for Chrome for unknown reason
  63845. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63846. if (!this._babylonGamepads[i].isConnected) {
  63847. this._babylonGamepads[i]._isConnected = true;
  63848. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63849. }
  63850. }
  63851. }
  63852. }
  63853. };
  63854. return GamepadManager;
  63855. }());
  63856. BABYLON.GamepadManager = GamepadManager;
  63857. })(BABYLON || (BABYLON = {}));
  63858. //# sourceMappingURL=babylon.gamepadManager.js.map
  63859. var BABYLON;
  63860. (function (BABYLON) {
  63861. var StickValues = /** @class */ (function () {
  63862. function StickValues(x, y) {
  63863. this.x = x;
  63864. this.y = y;
  63865. }
  63866. return StickValues;
  63867. }());
  63868. BABYLON.StickValues = StickValues;
  63869. var Gamepad = /** @class */ (function () {
  63870. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63871. if (leftStickX === void 0) { leftStickX = 0; }
  63872. if (leftStickY === void 0) { leftStickY = 1; }
  63873. if (rightStickX === void 0) { rightStickX = 2; }
  63874. if (rightStickY === void 0) { rightStickY = 3; }
  63875. this.id = id;
  63876. this.index = index;
  63877. this.browserGamepad = browserGamepad;
  63878. this._isConnected = true;
  63879. this._invertLeftStickY = false;
  63880. this.type = Gamepad.GAMEPAD;
  63881. this._leftStickAxisX = leftStickX;
  63882. this._leftStickAxisY = leftStickY;
  63883. this._rightStickAxisX = rightStickX;
  63884. this._rightStickAxisY = rightStickY;
  63885. if (this.browserGamepad.axes.length >= 2) {
  63886. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63887. }
  63888. if (this.browserGamepad.axes.length >= 4) {
  63889. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63890. }
  63891. }
  63892. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63893. get: function () {
  63894. return this._isConnected;
  63895. },
  63896. enumerable: true,
  63897. configurable: true
  63898. });
  63899. Gamepad.prototype.onleftstickchanged = function (callback) {
  63900. this._onleftstickchanged = callback;
  63901. };
  63902. Gamepad.prototype.onrightstickchanged = function (callback) {
  63903. this._onrightstickchanged = callback;
  63904. };
  63905. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63906. get: function () {
  63907. return this._leftStick;
  63908. },
  63909. set: function (newValues) {
  63910. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63911. this._onleftstickchanged(newValues);
  63912. }
  63913. this._leftStick = newValues;
  63914. },
  63915. enumerable: true,
  63916. configurable: true
  63917. });
  63918. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63919. get: function () {
  63920. return this._rightStick;
  63921. },
  63922. set: function (newValues) {
  63923. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63924. this._onrightstickchanged(newValues);
  63925. }
  63926. this._rightStick = newValues;
  63927. },
  63928. enumerable: true,
  63929. configurable: true
  63930. });
  63931. Gamepad.prototype.update = function () {
  63932. if (this._leftStick) {
  63933. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63934. if (this._invertLeftStickY) {
  63935. this.leftStick.y *= -1;
  63936. }
  63937. }
  63938. if (this._rightStick) {
  63939. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63940. }
  63941. };
  63942. Gamepad.prototype.dispose = function () {
  63943. };
  63944. Gamepad.GAMEPAD = 0;
  63945. Gamepad.GENERIC = 1;
  63946. Gamepad.XBOX = 2;
  63947. Gamepad.POSE_ENABLED = 3;
  63948. return Gamepad;
  63949. }());
  63950. BABYLON.Gamepad = Gamepad;
  63951. var GenericPad = /** @class */ (function (_super) {
  63952. __extends(GenericPad, _super);
  63953. function GenericPad(id, index, browserGamepad) {
  63954. var _this = _super.call(this, id, index, browserGamepad) || this;
  63955. _this.onButtonDownObservable = new BABYLON.Observable();
  63956. _this.onButtonUpObservable = new BABYLON.Observable();
  63957. _this.type = Gamepad.GENERIC;
  63958. _this._buttons = new Array(browserGamepad.buttons.length);
  63959. return _this;
  63960. }
  63961. GenericPad.prototype.onbuttondown = function (callback) {
  63962. this._onbuttondown = callback;
  63963. };
  63964. GenericPad.prototype.onbuttonup = function (callback) {
  63965. this._onbuttonup = callback;
  63966. };
  63967. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63968. if (newValue !== currentValue) {
  63969. if (newValue === 1) {
  63970. if (this._onbuttondown) {
  63971. this._onbuttondown(buttonIndex);
  63972. }
  63973. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63974. }
  63975. if (newValue === 0) {
  63976. if (this._onbuttonup) {
  63977. this._onbuttonup(buttonIndex);
  63978. }
  63979. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63980. }
  63981. }
  63982. return newValue;
  63983. };
  63984. GenericPad.prototype.update = function () {
  63985. _super.prototype.update.call(this);
  63986. for (var index = 0; index < this._buttons.length; index++) {
  63987. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63988. }
  63989. };
  63990. GenericPad.prototype.dispose = function () {
  63991. _super.prototype.dispose.call(this);
  63992. this.onButtonDownObservable.clear();
  63993. this.onButtonUpObservable.clear();
  63994. };
  63995. return GenericPad;
  63996. }(Gamepad));
  63997. BABYLON.GenericPad = GenericPad;
  63998. })(BABYLON || (BABYLON = {}));
  63999. //# sourceMappingURL=babylon.gamepad.js.map
  64000. var BABYLON;
  64001. (function (BABYLON) {
  64002. var Xbox360Button;
  64003. (function (Xbox360Button) {
  64004. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64005. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64006. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64007. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64008. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64009. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64010. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64011. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64012. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64013. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64014. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64015. var Xbox360Dpad;
  64016. (function (Xbox360Dpad) {
  64017. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64018. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64019. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64020. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64021. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64022. var Xbox360Pad = /** @class */ (function (_super) {
  64023. __extends(Xbox360Pad, _super);
  64024. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64025. if (xboxOne === void 0) { xboxOne = false; }
  64026. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64027. _this._leftTrigger = 0;
  64028. _this._rightTrigger = 0;
  64029. _this.onButtonDownObservable = new BABYLON.Observable();
  64030. _this.onButtonUpObservable = new BABYLON.Observable();
  64031. _this.onPadDownObservable = new BABYLON.Observable();
  64032. _this.onPadUpObservable = new BABYLON.Observable();
  64033. _this._buttonA = 0;
  64034. _this._buttonB = 0;
  64035. _this._buttonX = 0;
  64036. _this._buttonY = 0;
  64037. _this._buttonBack = 0;
  64038. _this._buttonStart = 0;
  64039. _this._buttonLB = 0;
  64040. _this._buttonRB = 0;
  64041. _this._buttonLeftStick = 0;
  64042. _this._buttonRightStick = 0;
  64043. _this._dPadUp = 0;
  64044. _this._dPadDown = 0;
  64045. _this._dPadLeft = 0;
  64046. _this._dPadRight = 0;
  64047. _this._isXboxOnePad = false;
  64048. _this.type = BABYLON.Gamepad.XBOX;
  64049. _this._isXboxOnePad = xboxOne;
  64050. return _this;
  64051. }
  64052. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64053. this._onlefttriggerchanged = callback;
  64054. };
  64055. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64056. this._onrighttriggerchanged = callback;
  64057. };
  64058. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64059. get: function () {
  64060. return this._leftTrigger;
  64061. },
  64062. set: function (newValue) {
  64063. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64064. this._onlefttriggerchanged(newValue);
  64065. }
  64066. this._leftTrigger = newValue;
  64067. },
  64068. enumerable: true,
  64069. configurable: true
  64070. });
  64071. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64072. get: function () {
  64073. return this._rightTrigger;
  64074. },
  64075. set: function (newValue) {
  64076. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64077. this._onrighttriggerchanged(newValue);
  64078. }
  64079. this._rightTrigger = newValue;
  64080. },
  64081. enumerable: true,
  64082. configurable: true
  64083. });
  64084. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64085. this._onbuttondown = callback;
  64086. };
  64087. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64088. this._onbuttonup = callback;
  64089. };
  64090. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64091. this._ondpaddown = callback;
  64092. };
  64093. Xbox360Pad.prototype.ondpadup = function (callback) {
  64094. this._ondpadup = callback;
  64095. };
  64096. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64097. if (newValue !== currentValue) {
  64098. if (newValue === 1) {
  64099. if (this._onbuttondown) {
  64100. this._onbuttondown(buttonType);
  64101. }
  64102. this.onButtonDownObservable.notifyObservers(buttonType);
  64103. }
  64104. if (newValue === 0) {
  64105. if (this._onbuttonup) {
  64106. this._onbuttonup(buttonType);
  64107. }
  64108. this.onButtonUpObservable.notifyObservers(buttonType);
  64109. }
  64110. }
  64111. return newValue;
  64112. };
  64113. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64114. if (newValue !== currentValue) {
  64115. if (newValue === 1) {
  64116. if (this._ondpaddown) {
  64117. this._ondpaddown(buttonType);
  64118. }
  64119. this.onPadDownObservable.notifyObservers(buttonType);
  64120. }
  64121. if (newValue === 0) {
  64122. if (this._ondpadup) {
  64123. this._ondpadup(buttonType);
  64124. }
  64125. this.onPadUpObservable.notifyObservers(buttonType);
  64126. }
  64127. }
  64128. return newValue;
  64129. };
  64130. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64131. get: function () {
  64132. return this._buttonA;
  64133. },
  64134. set: function (value) {
  64135. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64136. },
  64137. enumerable: true,
  64138. configurable: true
  64139. });
  64140. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64141. get: function () {
  64142. return this._buttonB;
  64143. },
  64144. set: function (value) {
  64145. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64151. get: function () {
  64152. return this._buttonX;
  64153. },
  64154. set: function (value) {
  64155. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64156. },
  64157. enumerable: true,
  64158. configurable: true
  64159. });
  64160. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64161. get: function () {
  64162. return this._buttonY;
  64163. },
  64164. set: function (value) {
  64165. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64166. },
  64167. enumerable: true,
  64168. configurable: true
  64169. });
  64170. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64171. get: function () {
  64172. return this._buttonStart;
  64173. },
  64174. set: function (value) {
  64175. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64181. get: function () {
  64182. return this._buttonBack;
  64183. },
  64184. set: function (value) {
  64185. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64186. },
  64187. enumerable: true,
  64188. configurable: true
  64189. });
  64190. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64191. get: function () {
  64192. return this._buttonLB;
  64193. },
  64194. set: function (value) {
  64195. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64201. get: function () {
  64202. return this._buttonRB;
  64203. },
  64204. set: function (value) {
  64205. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64206. },
  64207. enumerable: true,
  64208. configurable: true
  64209. });
  64210. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64211. get: function () {
  64212. return this._buttonLeftStick;
  64213. },
  64214. set: function (value) {
  64215. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64216. },
  64217. enumerable: true,
  64218. configurable: true
  64219. });
  64220. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64221. get: function () {
  64222. return this._buttonRightStick;
  64223. },
  64224. set: function (value) {
  64225. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64226. },
  64227. enumerable: true,
  64228. configurable: true
  64229. });
  64230. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64231. get: function () {
  64232. return this._dPadUp;
  64233. },
  64234. set: function (value) {
  64235. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64236. },
  64237. enumerable: true,
  64238. configurable: true
  64239. });
  64240. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64241. get: function () {
  64242. return this._dPadDown;
  64243. },
  64244. set: function (value) {
  64245. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64246. },
  64247. enumerable: true,
  64248. configurable: true
  64249. });
  64250. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64251. get: function () {
  64252. return this._dPadLeft;
  64253. },
  64254. set: function (value) {
  64255. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64256. },
  64257. enumerable: true,
  64258. configurable: true
  64259. });
  64260. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64261. get: function () {
  64262. return this._dPadRight;
  64263. },
  64264. set: function (value) {
  64265. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64266. },
  64267. enumerable: true,
  64268. configurable: true
  64269. });
  64270. Xbox360Pad.prototype.update = function () {
  64271. _super.prototype.update.call(this);
  64272. if (this._isXboxOnePad) {
  64273. this.buttonA = this.browserGamepad.buttons[0].value;
  64274. this.buttonB = this.browserGamepad.buttons[1].value;
  64275. this.buttonX = this.browserGamepad.buttons[2].value;
  64276. this.buttonY = this.browserGamepad.buttons[3].value;
  64277. this.buttonLB = this.browserGamepad.buttons[4].value;
  64278. this.buttonRB = this.browserGamepad.buttons[5].value;
  64279. this.leftTrigger = this.browserGamepad.axes[2];
  64280. this.rightTrigger = this.browserGamepad.axes[5];
  64281. this.buttonBack = this.browserGamepad.buttons[9].value;
  64282. this.buttonStart = this.browserGamepad.buttons[8].value;
  64283. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64284. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64285. this.dPadUp = this.browserGamepad.buttons[11].value;
  64286. this.dPadDown = this.browserGamepad.buttons[12].value;
  64287. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64288. this.dPadRight = this.browserGamepad.buttons[14].value;
  64289. }
  64290. else {
  64291. this.buttonA = this.browserGamepad.buttons[0].value;
  64292. this.buttonB = this.browserGamepad.buttons[1].value;
  64293. this.buttonX = this.browserGamepad.buttons[2].value;
  64294. this.buttonY = this.browserGamepad.buttons[3].value;
  64295. this.buttonLB = this.browserGamepad.buttons[4].value;
  64296. this.buttonRB = this.browserGamepad.buttons[5].value;
  64297. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64298. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64299. this.buttonBack = this.browserGamepad.buttons[8].value;
  64300. this.buttonStart = this.browserGamepad.buttons[9].value;
  64301. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64302. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64303. this.dPadUp = this.browserGamepad.buttons[12].value;
  64304. this.dPadDown = this.browserGamepad.buttons[13].value;
  64305. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64306. this.dPadRight = this.browserGamepad.buttons[15].value;
  64307. }
  64308. };
  64309. Xbox360Pad.prototype.dispose = function () {
  64310. _super.prototype.dispose.call(this);
  64311. this.onButtonDownObservable.clear();
  64312. this.onButtonUpObservable.clear();
  64313. this.onPadDownObservable.clear();
  64314. this.onPadUpObservable.clear();
  64315. };
  64316. return Xbox360Pad;
  64317. }(BABYLON.Gamepad));
  64318. BABYLON.Xbox360Pad = Xbox360Pad;
  64319. })(BABYLON || (BABYLON = {}));
  64320. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64321. var BABYLON;
  64322. (function (BABYLON) {
  64323. var PoseEnabledControllerType;
  64324. (function (PoseEnabledControllerType) {
  64325. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64326. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64327. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64328. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64329. /**
  64330. * Google Daydream
  64331. */
  64332. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64333. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64334. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64335. var PoseEnabledControllerHelper = /** @class */ (function () {
  64336. function PoseEnabledControllerHelper() {
  64337. }
  64338. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64339. // Oculus Touch
  64340. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64341. return new BABYLON.OculusTouchController(vrGamepad);
  64342. }
  64343. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64344. return new BABYLON.WindowsMotionController(vrGamepad);
  64345. }
  64346. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64347. return new BABYLON.ViveController(vrGamepad);
  64348. }
  64349. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64350. return new BABYLON.GearVRController(vrGamepad);
  64351. }
  64352. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64353. return new BABYLON.DaydreamController(vrGamepad);
  64354. }
  64355. else {
  64356. return new BABYLON.GenericController(vrGamepad);
  64357. }
  64358. };
  64359. return PoseEnabledControllerHelper;
  64360. }());
  64361. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64362. var PoseEnabledController = /** @class */ (function (_super) {
  64363. __extends(PoseEnabledController, _super);
  64364. function PoseEnabledController(browserGamepad) {
  64365. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64366. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64367. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64368. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64369. // Represents device position and rotation in babylon space
  64370. _this.devicePosition = BABYLON.Vector3.Zero();
  64371. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64372. _this.deviceScaleFactor = 1;
  64373. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64374. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64375. /**
  64376. * Node to be used when casting a ray from the controller
  64377. */
  64378. _this._pointingPoseNode = null;
  64379. _this._workingMatrix = BABYLON.Matrix.Identity();
  64380. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64381. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64382. _this.position = BABYLON.Vector3.Zero();
  64383. _this.rotationQuaternion = new BABYLON.Quaternion();
  64384. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64385. _this._calculatedRotation = new BABYLON.Quaternion();
  64386. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64387. return _this;
  64388. }
  64389. PoseEnabledController.prototype.update = function () {
  64390. _super.prototype.update.call(this);
  64391. var pose = this.browserGamepad.pose;
  64392. this.updateFromDevice(pose);
  64393. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64394. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64395. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64396. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64397. if (this._mesh) {
  64398. this._mesh.position.copyFrom(this.devicePosition);
  64399. if (this._mesh.rotationQuaternion) {
  64400. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64401. }
  64402. }
  64403. };
  64404. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64405. if (poseData) {
  64406. this.rawPose = poseData;
  64407. if (poseData.position) {
  64408. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64409. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64410. this._deviceRoomPosition.z *= -1;
  64411. }
  64412. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64413. this._calculatedPosition.addInPlace(this.position);
  64414. }
  64415. var pose = this.rawPose;
  64416. if (poseData.orientation && pose.orientation) {
  64417. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64418. if (this._mesh) {
  64419. if (this._mesh.getScene().useRightHandedSystem) {
  64420. this._deviceRoomRotationQuaternion.z *= -1;
  64421. this._deviceRoomRotationQuaternion.w *= -1;
  64422. }
  64423. else {
  64424. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64425. }
  64426. }
  64427. // if the camera is set, rotate to the camera's rotation
  64428. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64429. }
  64430. }
  64431. };
  64432. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64433. if (this._mesh) {
  64434. this._mesh.parent = null;
  64435. }
  64436. this._mesh = mesh;
  64437. if (this._poseControlledCamera) {
  64438. this._mesh.parent = this._poseControlledCamera;
  64439. }
  64440. if (!this._mesh.rotationQuaternion) {
  64441. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64442. }
  64443. };
  64444. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64445. this._poseControlledCamera = camera;
  64446. if (this._mesh) {
  64447. this._mesh.parent = this._poseControlledCamera;
  64448. }
  64449. };
  64450. PoseEnabledController.prototype.dispose = function () {
  64451. if (this._mesh) {
  64452. this._mesh.dispose();
  64453. }
  64454. this._mesh = null;
  64455. _super.prototype.dispose.call(this);
  64456. };
  64457. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64458. get: function () {
  64459. return this._mesh;
  64460. },
  64461. enumerable: true,
  64462. configurable: true
  64463. });
  64464. PoseEnabledController.prototype.getForwardRay = function (length) {
  64465. if (length === void 0) { length = 100; }
  64466. if (!this.mesh) {
  64467. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64468. }
  64469. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64470. var origin = m.getTranslation();
  64471. var forward = new BABYLON.Vector3(0, 0, -1);
  64472. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64473. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64474. return new BABYLON.Ray(origin, direction, length);
  64475. };
  64476. /**
  64477. * Name of the child mesh that can be used to cast a ray from the controller
  64478. */
  64479. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64480. return PoseEnabledController;
  64481. }(BABYLON.Gamepad));
  64482. BABYLON.PoseEnabledController = PoseEnabledController;
  64483. })(BABYLON || (BABYLON = {}));
  64484. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64485. var BABYLON;
  64486. (function (BABYLON) {
  64487. var WebVRController = /** @class */ (function (_super) {
  64488. __extends(WebVRController, _super);
  64489. function WebVRController(vrGamepad) {
  64490. var _this = _super.call(this, vrGamepad) || this;
  64491. // Observables
  64492. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64493. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64494. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64495. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64496. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64497. _this.pad = { x: 0, y: 0 };
  64498. // avoid GC, store state in a tmp object
  64499. _this._changes = {
  64500. pressChanged: false,
  64501. touchChanged: false,
  64502. valueChanged: false,
  64503. changed: false
  64504. };
  64505. _this._buttons = new Array(vrGamepad.buttons.length);
  64506. _this.hand = vrGamepad.hand;
  64507. return _this;
  64508. }
  64509. WebVRController.prototype.onButtonStateChange = function (callback) {
  64510. this._onButtonStateChange = callback;
  64511. };
  64512. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64513. get: function () {
  64514. return this._defaultModel;
  64515. },
  64516. enumerable: true,
  64517. configurable: true
  64518. });
  64519. WebVRController.prototype.update = function () {
  64520. _super.prototype.update.call(this);
  64521. for (var index = 0; index < this._buttons.length; index++) {
  64522. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64523. }
  64524. ;
  64525. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64526. this.pad.x = this.leftStick.x;
  64527. this.pad.y = this.leftStick.y;
  64528. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64529. }
  64530. };
  64531. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64532. if (!newState) {
  64533. newState = {
  64534. pressed: false,
  64535. touched: false,
  64536. value: 0
  64537. };
  64538. }
  64539. if (!currentState) {
  64540. this._buttons[buttonIndex] = {
  64541. pressed: newState.pressed,
  64542. touched: newState.touched,
  64543. value: newState.value
  64544. };
  64545. return;
  64546. }
  64547. this._checkChanges(newState, currentState);
  64548. if (this._changes.changed) {
  64549. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64550. this._handleButtonChange(buttonIndex, newState, this._changes);
  64551. }
  64552. this._buttons[buttonIndex].pressed = newState.pressed;
  64553. this._buttons[buttonIndex].touched = newState.touched;
  64554. // oculus triggers are never 0, thou not touched.
  64555. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64556. };
  64557. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64558. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64559. this._changes.touchChanged = newState.touched !== currentState.touched;
  64560. this._changes.valueChanged = newState.value !== currentState.value;
  64561. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64562. return this._changes;
  64563. };
  64564. WebVRController.prototype.dispose = function () {
  64565. _super.prototype.dispose.call(this);
  64566. this.onTriggerStateChangedObservable.clear();
  64567. this.onMainButtonStateChangedObservable.clear();
  64568. this.onSecondaryButtonStateChangedObservable.clear();
  64569. this.onPadStateChangedObservable.clear();
  64570. this.onPadValuesChangedObservable.clear();
  64571. };
  64572. return WebVRController;
  64573. }(BABYLON.PoseEnabledController));
  64574. BABYLON.WebVRController = WebVRController;
  64575. })(BABYLON || (BABYLON = {}));
  64576. //# sourceMappingURL=babylon.webVRController.js.map
  64577. var BABYLON;
  64578. (function (BABYLON) {
  64579. var OculusTouchController = /** @class */ (function (_super) {
  64580. __extends(OculusTouchController, _super);
  64581. function OculusTouchController(vrGamepad) {
  64582. var _this = _super.call(this, vrGamepad) || this;
  64583. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64584. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64585. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64586. return _this;
  64587. }
  64588. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64589. var _this = this;
  64590. var meshName;
  64591. // Hand
  64592. if (this.hand === 'left') {
  64593. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64594. }
  64595. else {
  64596. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64597. }
  64598. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64599. /*
  64600. Parent Mesh name: oculus_touch_left
  64601. - body
  64602. - trigger
  64603. - thumbstick
  64604. - grip
  64605. - button_y
  64606. - button_x
  64607. - button_enter
  64608. */
  64609. _this._defaultModel = newMeshes[1];
  64610. _this.attachToMesh(_this._defaultModel);
  64611. if (meshLoaded) {
  64612. meshLoaded(_this._defaultModel);
  64613. }
  64614. });
  64615. };
  64616. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64617. // helper getters for left and right hand.
  64618. get: function () {
  64619. if (this.hand === 'right') {
  64620. return this.onMainButtonStateChangedObservable;
  64621. }
  64622. else {
  64623. throw new Error('No A button on left hand');
  64624. }
  64625. },
  64626. enumerable: true,
  64627. configurable: true
  64628. });
  64629. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64630. get: function () {
  64631. if (this.hand === 'right') {
  64632. return this.onSecondaryButtonStateChangedObservable;
  64633. }
  64634. else {
  64635. throw new Error('No B button on left hand');
  64636. }
  64637. },
  64638. enumerable: true,
  64639. configurable: true
  64640. });
  64641. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64642. get: function () {
  64643. if (this.hand === 'left') {
  64644. return this.onMainButtonStateChangedObservable;
  64645. }
  64646. else {
  64647. throw new Error('No X button on right hand');
  64648. }
  64649. },
  64650. enumerable: true,
  64651. configurable: true
  64652. });
  64653. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64654. get: function () {
  64655. if (this.hand === 'left') {
  64656. return this.onSecondaryButtonStateChangedObservable;
  64657. }
  64658. else {
  64659. throw new Error('No Y button on right hand');
  64660. }
  64661. },
  64662. enumerable: true,
  64663. configurable: true
  64664. });
  64665. /*
  64666. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64667. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64668. 2) secondary trigger (same)
  64669. 3) A (right) X (left), touch, pressed = value
  64670. 4) B / Y
  64671. 5) thumb rest
  64672. */
  64673. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64674. var notifyObject = state; //{ state: state, changes: changes };
  64675. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64676. switch (buttonIdx) {
  64677. case 0:
  64678. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64679. return;
  64680. case 1:// index trigger
  64681. if (this._defaultModel) {
  64682. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64683. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64684. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64685. }
  64686. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64687. return;
  64688. case 2:// secondary trigger
  64689. if (this._defaultModel) {
  64690. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64691. }
  64692. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64693. return;
  64694. case 3:
  64695. if (this._defaultModel) {
  64696. if (notifyObject.pressed) {
  64697. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64698. }
  64699. else {
  64700. (this._defaultModel.getChildren()[1]).position.y = 0;
  64701. }
  64702. }
  64703. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64704. return;
  64705. case 4:
  64706. if (this._defaultModel) {
  64707. if (notifyObject.pressed) {
  64708. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64709. }
  64710. else {
  64711. (this._defaultModel.getChildren()[2]).position.y = 0;
  64712. }
  64713. }
  64714. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64715. return;
  64716. case 5:
  64717. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64718. return;
  64719. }
  64720. };
  64721. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64722. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64723. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64724. return OculusTouchController;
  64725. }(BABYLON.WebVRController));
  64726. BABYLON.OculusTouchController = OculusTouchController;
  64727. })(BABYLON || (BABYLON = {}));
  64728. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64729. var BABYLON;
  64730. (function (BABYLON) {
  64731. var ViveController = /** @class */ (function (_super) {
  64732. __extends(ViveController, _super);
  64733. function ViveController(vrGamepad) {
  64734. var _this = _super.call(this, vrGamepad) || this;
  64735. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64736. _this._invertLeftStickY = true;
  64737. return _this;
  64738. }
  64739. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64740. var _this = this;
  64741. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64742. /*
  64743. Parent Mesh name: ViveWand
  64744. - body
  64745. - r_gripper
  64746. - l_gripper
  64747. - menu_button
  64748. - system_button
  64749. - trackpad
  64750. - trigger
  64751. - LED
  64752. */
  64753. _this._defaultModel = newMeshes[1];
  64754. _this.attachToMesh(_this._defaultModel);
  64755. if (meshLoaded) {
  64756. meshLoaded(_this._defaultModel);
  64757. }
  64758. });
  64759. };
  64760. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64761. get: function () {
  64762. return this.onMainButtonStateChangedObservable;
  64763. },
  64764. enumerable: true,
  64765. configurable: true
  64766. });
  64767. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64768. get: function () {
  64769. return this.onMainButtonStateChangedObservable;
  64770. },
  64771. enumerable: true,
  64772. configurable: true
  64773. });
  64774. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64775. get: function () {
  64776. return this.onSecondaryButtonStateChangedObservable;
  64777. },
  64778. enumerable: true,
  64779. configurable: true
  64780. });
  64781. /**
  64782. * Vive mapping:
  64783. * 0: touchpad
  64784. * 1: trigger
  64785. * 2: left AND right buttons
  64786. * 3: menu button
  64787. */
  64788. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64789. var notifyObject = state; //{ state: state, changes: changes };
  64790. switch (buttonIdx) {
  64791. case 0:
  64792. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64793. return;
  64794. case 1:// index trigger
  64795. if (this._defaultModel) {
  64796. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64797. }
  64798. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64799. return;
  64800. case 2:// left AND right button
  64801. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64802. return;
  64803. case 3:
  64804. if (this._defaultModel) {
  64805. if (notifyObject.pressed) {
  64806. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64807. }
  64808. else {
  64809. (this._defaultModel.getChildren()[2]).position.y = 0;
  64810. }
  64811. }
  64812. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64813. return;
  64814. }
  64815. };
  64816. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64817. ViveController.MODEL_FILENAME = 'wand.babylon';
  64818. return ViveController;
  64819. }(BABYLON.WebVRController));
  64820. BABYLON.ViveController = ViveController;
  64821. })(BABYLON || (BABYLON = {}));
  64822. //# sourceMappingURL=babylon.viveController.js.map
  64823. var BABYLON;
  64824. (function (BABYLON) {
  64825. var GenericController = /** @class */ (function (_super) {
  64826. __extends(GenericController, _super);
  64827. function GenericController(vrGamepad) {
  64828. return _super.call(this, vrGamepad) || this;
  64829. }
  64830. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64831. var _this = this;
  64832. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64833. _this._defaultModel = newMeshes[1];
  64834. _this.attachToMesh(_this._defaultModel);
  64835. if (meshLoaded) {
  64836. meshLoaded(_this._defaultModel);
  64837. }
  64838. });
  64839. };
  64840. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64841. console.log("Button id: " + buttonIdx + "state: ");
  64842. console.dir(state);
  64843. };
  64844. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64845. GenericController.MODEL_FILENAME = 'generic.babylon';
  64846. return GenericController;
  64847. }(BABYLON.WebVRController));
  64848. BABYLON.GenericController = GenericController;
  64849. })(BABYLON || (BABYLON = {}));
  64850. //# sourceMappingURL=babylon.genericController.js.map
  64851. var BABYLON;
  64852. (function (BABYLON) {
  64853. var LoadedMeshInfo = /** @class */ (function () {
  64854. function LoadedMeshInfo() {
  64855. this.buttonMeshes = {};
  64856. this.axisMeshes = {};
  64857. }
  64858. return LoadedMeshInfo;
  64859. }());
  64860. var WindowsMotionController = /** @class */ (function (_super) {
  64861. __extends(WindowsMotionController, _super);
  64862. function WindowsMotionController(vrGamepad) {
  64863. var _this = _super.call(this, vrGamepad) || this;
  64864. _this._mapping = {
  64865. // Semantic button names
  64866. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64867. // A mapping of the button name to glTF model node name
  64868. // that should be transformed by button value.
  64869. buttonMeshNames: {
  64870. 'trigger': 'SELECT',
  64871. 'menu': 'MENU',
  64872. 'grip': 'GRASP',
  64873. 'thumbstick': 'THUMBSTICK_PRESS',
  64874. 'trackpad': 'TOUCHPAD_PRESS'
  64875. },
  64876. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64877. buttonObservableNames: {
  64878. 'trigger': 'onTriggerStateChangedObservable',
  64879. 'menu': 'onSecondaryButtonStateChangedObservable',
  64880. 'grip': 'onMainButtonStateChangedObservable',
  64881. 'thumbstick': 'onPadStateChangedObservable',
  64882. 'trackpad': 'onTrackpadChangedObservable'
  64883. },
  64884. // A mapping of the axis name to glTF model node name
  64885. // that should be transformed by axis value.
  64886. // This array mirrors the browserGamepad.axes array, such that
  64887. // the mesh corresponding to axis 0 is in this array index 0.
  64888. axisMeshNames: [
  64889. 'THUMBSTICK_X',
  64890. 'THUMBSTICK_Y',
  64891. 'TOUCHPAD_TOUCH_X',
  64892. 'TOUCHPAD_TOUCH_Y'
  64893. ],
  64894. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  64895. };
  64896. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64897. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64898. _this.trackpad = { x: 0, y: 0 };
  64899. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64900. _this._loadedMeshInfo = null;
  64901. return _this;
  64902. }
  64903. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64904. get: function () {
  64905. return this.onTriggerStateChangedObservable;
  64906. },
  64907. enumerable: true,
  64908. configurable: true
  64909. });
  64910. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64911. get: function () {
  64912. return this.onSecondaryButtonStateChangedObservable;
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64918. get: function () {
  64919. return this.onMainButtonStateChangedObservable;
  64920. },
  64921. enumerable: true,
  64922. configurable: true
  64923. });
  64924. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64925. get: function () {
  64926. return this.onPadStateChangedObservable;
  64927. },
  64928. enumerable: true,
  64929. configurable: true
  64930. });
  64931. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64932. get: function () {
  64933. return this.onTrackpadChangedObservable;
  64934. },
  64935. enumerable: true,
  64936. configurable: true
  64937. });
  64938. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64939. get: function () {
  64940. return this.onTrackpadValuesChangedObservable;
  64941. },
  64942. enumerable: true,
  64943. configurable: true
  64944. });
  64945. /**
  64946. * Called once per frame by the engine.
  64947. */
  64948. WindowsMotionController.prototype.update = function () {
  64949. _super.prototype.update.call(this);
  64950. if (this.browserGamepad.axes) {
  64951. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64952. this.trackpad.x = this.browserGamepad["axes"][2];
  64953. this.trackpad.y = this.browserGamepad["axes"][3];
  64954. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64955. }
  64956. // Only need to animate axes if there is a loaded mesh
  64957. if (this._loadedMeshInfo) {
  64958. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64959. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64960. }
  64961. }
  64962. }
  64963. };
  64964. /**
  64965. * Called once for each button that changed state since the last frame
  64966. * @param buttonIdx Which button index changed
  64967. * @param state New state of the button
  64968. * @param changes Which properties on the state changed since last frame
  64969. */
  64970. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64971. var buttonName = this._mapping.buttons[buttonIdx];
  64972. if (!buttonName) {
  64973. return;
  64974. }
  64975. // Only emit events for buttons that we know how to map from index to name
  64976. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64977. if (observable) {
  64978. observable.notifyObservers(state);
  64979. }
  64980. this.lerpButtonTransform(buttonName, state.value);
  64981. };
  64982. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64983. // If there is no loaded mesh, there is nothing to transform.
  64984. if (!this._loadedMeshInfo) {
  64985. return;
  64986. }
  64987. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64988. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64989. return;
  64990. }
  64991. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64992. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64993. };
  64994. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64995. if (!this._loadedMeshInfo) {
  64996. return;
  64997. }
  64998. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64999. if (!meshInfo) {
  65000. return;
  65001. }
  65002. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65003. return;
  65004. }
  65005. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65006. var lerpValue = axisValue * 0.5 + 0.5;
  65007. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65008. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65009. };
  65010. /**
  65011. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65012. * @param scene scene in which to add meshes
  65013. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65014. */
  65015. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65016. var _this = this;
  65017. if (forceDefault === void 0) { forceDefault = false; }
  65018. var path;
  65019. var filename;
  65020. // Checking if GLB loader is present
  65021. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65022. // Determine the device specific folder based on the ID suffix
  65023. var device = 'default';
  65024. if (this.id && !forceDefault) {
  65025. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65026. device = ((match && match[0]) || device);
  65027. }
  65028. // Hand
  65029. if (this.hand === 'left') {
  65030. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65031. }
  65032. else {
  65033. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65034. }
  65035. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65036. }
  65037. else {
  65038. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65039. path = BABYLON.GenericController.MODEL_BASE_URL;
  65040. filename = BABYLON.GenericController.MODEL_FILENAME;
  65041. }
  65042. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65043. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65044. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65045. if (!_this._loadedMeshInfo) {
  65046. return;
  65047. }
  65048. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65049. _this.attachToMesh(_this._defaultModel);
  65050. if (meshLoaded) {
  65051. meshLoaded(_this._defaultModel);
  65052. }
  65053. }, null, function (scene, message) {
  65054. BABYLON.Tools.Log(message);
  65055. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65056. if (!forceDefault) {
  65057. _this.initControllerMesh(scene, meshLoaded, true);
  65058. }
  65059. });
  65060. };
  65061. /**
  65062. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65063. * can be transformed by button presses and axes values, based on this._mapping.
  65064. *
  65065. * @param scene scene in which the meshes exist
  65066. * @param meshes list of meshes that make up the controller model to process
  65067. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65068. */
  65069. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65070. var loadedMeshInfo = null;
  65071. // Create a new mesh to contain the glTF hierarchy
  65072. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65073. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65074. var childMesh = null;
  65075. for (var i = 0; i < meshes.length; i++) {
  65076. var mesh = meshes[i];
  65077. if (!mesh.parent) {
  65078. // Exclude controller meshes from picking results
  65079. mesh.isPickable = false;
  65080. // Handle root node, attach to the new parentMesh
  65081. childMesh = mesh;
  65082. break;
  65083. }
  65084. }
  65085. if (childMesh) {
  65086. childMesh.setParent(parentMesh);
  65087. // Create our mesh info. Note that this method will always return non-null.
  65088. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65089. }
  65090. else {
  65091. BABYLON.Tools.Warn('Could not find root node in model file.');
  65092. }
  65093. return loadedMeshInfo;
  65094. };
  65095. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65096. var loadedMeshInfo = new LoadedMeshInfo();
  65097. var i;
  65098. loadedMeshInfo.rootNode = rootNode;
  65099. // Reset the caches
  65100. loadedMeshInfo.buttonMeshes = {};
  65101. loadedMeshInfo.axisMeshes = {};
  65102. // Button Meshes
  65103. for (i = 0; i < this._mapping.buttons.length; i++) {
  65104. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65105. if (!buttonMeshName) {
  65106. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65107. continue;
  65108. }
  65109. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65110. if (!buttonMesh) {
  65111. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65112. continue;
  65113. }
  65114. var buttonMeshInfo = {
  65115. index: i,
  65116. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65117. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65118. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65119. };
  65120. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65121. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65122. }
  65123. else {
  65124. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65125. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65126. '(VALUE: ' + !!buttonMeshInfo.value +
  65127. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65128. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65129. ')');
  65130. }
  65131. }
  65132. // Axis Meshes
  65133. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65134. var axisMeshName = this._mapping.axisMeshNames[i];
  65135. if (!axisMeshName) {
  65136. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65137. continue;
  65138. }
  65139. var axisMesh = getChildByName(rootNode, axisMeshName);
  65140. if (!axisMesh) {
  65141. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65142. continue;
  65143. }
  65144. var axisMeshInfo = {
  65145. index: i,
  65146. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65147. min: getImmediateChildByName(axisMesh, 'MIN'),
  65148. max: getImmediateChildByName(axisMesh, 'MAX')
  65149. };
  65150. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65151. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65152. }
  65153. else {
  65154. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65155. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65156. '(VALUE: ' + !!axisMeshInfo.value +
  65157. ', MIN: ' + !!axisMeshInfo.min +
  65158. ', MAX:' + !!axisMeshInfo.max +
  65159. ')');
  65160. }
  65161. }
  65162. // Pointing Ray
  65163. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65164. if (!loadedMeshInfo.pointingPoseNode) {
  65165. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65166. }
  65167. return loadedMeshInfo;
  65168. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65169. function getChildByName(node, name) {
  65170. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65171. }
  65172. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65173. function getImmediateChildByName(node, name) {
  65174. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65175. }
  65176. };
  65177. WindowsMotionController.prototype.getForwardRay = function (length) {
  65178. if (length === void 0) { length = 100; }
  65179. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65180. return _super.prototype.getForwardRay.call(this, length);
  65181. }
  65182. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65183. var origin = m.getTranslation();
  65184. var forward = new BABYLON.Vector3(0, 0, -1);
  65185. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65186. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65187. return new BABYLON.Ray(origin, direction, length);
  65188. };
  65189. WindowsMotionController.prototype.dispose = function () {
  65190. _super.prototype.dispose.call(this);
  65191. this.onTrackpadChangedObservable.clear();
  65192. };
  65193. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65194. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65195. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65196. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65197. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65198. return WindowsMotionController;
  65199. }(BABYLON.WebVRController));
  65200. BABYLON.WindowsMotionController = WindowsMotionController;
  65201. })(BABYLON || (BABYLON = {}));
  65202. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65203. var BABYLON;
  65204. (function (BABYLON) {
  65205. var GearVRController = /** @class */ (function (_super) {
  65206. __extends(GearVRController, _super);
  65207. function GearVRController(vrGamepad) {
  65208. var _this = _super.call(this, vrGamepad) || this;
  65209. _this._buttonIndexToObservableNameMap = [
  65210. 'onTrackpadChangedObservable',
  65211. 'onTriggerStateChangedObservable' // Trigger
  65212. ];
  65213. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65214. return _this;
  65215. }
  65216. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65217. var _this = this;
  65218. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65219. _this._defaultModel = newMeshes[1];
  65220. _this.attachToMesh(_this._defaultModel);
  65221. if (meshLoaded) {
  65222. meshLoaded(_this._defaultModel);
  65223. }
  65224. });
  65225. };
  65226. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65227. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65228. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65229. // Only emit events for buttons that we know how to map from index to observable
  65230. var observable = this[observableName];
  65231. if (observable) {
  65232. observable.notifyObservers(state);
  65233. }
  65234. }
  65235. };
  65236. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65237. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65238. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65239. return GearVRController;
  65240. }(BABYLON.WebVRController));
  65241. BABYLON.GearVRController = GearVRController;
  65242. })(BABYLON || (BABYLON = {}));
  65243. //# sourceMappingURL=babylon.gearVRController.js.map
  65244. var BABYLON;
  65245. (function (BABYLON) {
  65246. /**
  65247. * Google Daydream controller
  65248. */
  65249. var DaydreamController = /** @class */ (function (_super) {
  65250. __extends(DaydreamController, _super);
  65251. function DaydreamController(vrGamepad) {
  65252. var _this = _super.call(this, vrGamepad) || this;
  65253. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65254. return _this;
  65255. }
  65256. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65257. var _this = this;
  65258. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65259. _this._defaultModel = newMeshes[1];
  65260. _this.attachToMesh(_this._defaultModel);
  65261. if (meshLoaded) {
  65262. meshLoaded(_this._defaultModel);
  65263. }
  65264. });
  65265. };
  65266. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65267. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65268. if (buttonIdx === 0) {
  65269. var observable = this.onTriggerStateChangedObservable;
  65270. if (observable) {
  65271. observable.notifyObservers(state);
  65272. }
  65273. }
  65274. else {
  65275. // If the app or home buttons are ever made available
  65276. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65277. }
  65278. };
  65279. /**
  65280. * Base Url for the controller model.
  65281. */
  65282. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65283. /**
  65284. * File name for the controller model.
  65285. */
  65286. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65287. /**
  65288. * Gamepad Id prefix used to identify Daydream Controller.
  65289. */
  65290. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65291. return DaydreamController;
  65292. }(BABYLON.WebVRController));
  65293. BABYLON.DaydreamController = DaydreamController;
  65294. })(BABYLON || (BABYLON = {}));
  65295. //# sourceMappingURL=babylon.daydreamController.js.map
  65296. var BABYLON;
  65297. (function (BABYLON) {
  65298. var FollowCamera = /** @class */ (function (_super) {
  65299. __extends(FollowCamera, _super);
  65300. function FollowCamera(name, position, scene, lockedTarget) {
  65301. if (lockedTarget === void 0) { lockedTarget = null; }
  65302. var _this = _super.call(this, name, position, scene) || this;
  65303. _this.radius = 12;
  65304. _this.rotationOffset = 0;
  65305. _this.heightOffset = 4;
  65306. _this.cameraAcceleration = 0.05;
  65307. _this.maxCameraSpeed = 20;
  65308. _this.lockedTarget = lockedTarget;
  65309. return _this;
  65310. }
  65311. FollowCamera.prototype.getRadians = function (degrees) {
  65312. return degrees * Math.PI / 180;
  65313. };
  65314. FollowCamera.prototype.follow = function (cameraTarget) {
  65315. if (!cameraTarget)
  65316. return;
  65317. var yRotation;
  65318. if (cameraTarget.rotationQuaternion) {
  65319. var rotMatrix = new BABYLON.Matrix();
  65320. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65321. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65322. }
  65323. else {
  65324. yRotation = cameraTarget.rotation.y;
  65325. }
  65326. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65327. var targetPosition = cameraTarget.getAbsolutePosition();
  65328. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65329. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65330. var dx = targetX - this.position.x;
  65331. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65332. var dz = (targetZ) - this.position.z;
  65333. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65334. var vy = dy * this.cameraAcceleration;
  65335. var vz = dz * this.cameraAcceleration * 2;
  65336. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65337. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65338. }
  65339. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65340. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65341. }
  65342. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65343. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65344. }
  65345. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65346. this.setTarget(targetPosition);
  65347. };
  65348. FollowCamera.prototype._checkInputs = function () {
  65349. _super.prototype._checkInputs.call(this);
  65350. if (this.lockedTarget) {
  65351. this.follow(this.lockedTarget);
  65352. }
  65353. };
  65354. FollowCamera.prototype.getClassName = function () {
  65355. return "FollowCamera";
  65356. };
  65357. __decorate([
  65358. BABYLON.serialize()
  65359. ], FollowCamera.prototype, "radius", void 0);
  65360. __decorate([
  65361. BABYLON.serialize()
  65362. ], FollowCamera.prototype, "rotationOffset", void 0);
  65363. __decorate([
  65364. BABYLON.serialize()
  65365. ], FollowCamera.prototype, "heightOffset", void 0);
  65366. __decorate([
  65367. BABYLON.serialize()
  65368. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65369. __decorate([
  65370. BABYLON.serialize()
  65371. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65372. __decorate([
  65373. BABYLON.serializeAsMeshReference("lockedTargetId")
  65374. ], FollowCamera.prototype, "lockedTarget", void 0);
  65375. return FollowCamera;
  65376. }(BABYLON.TargetCamera));
  65377. BABYLON.FollowCamera = FollowCamera;
  65378. var ArcFollowCamera = /** @class */ (function (_super) {
  65379. __extends(ArcFollowCamera, _super);
  65380. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65381. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65382. _this.alpha = alpha;
  65383. _this.beta = beta;
  65384. _this.radius = radius;
  65385. _this.target = target;
  65386. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65387. _this.follow();
  65388. return _this;
  65389. }
  65390. ArcFollowCamera.prototype.follow = function () {
  65391. if (!this.target) {
  65392. return;
  65393. }
  65394. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65395. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65396. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65397. var targetPosition = this.target.getAbsolutePosition();
  65398. this.position = targetPosition.add(this._cartesianCoordinates);
  65399. this.setTarget(targetPosition);
  65400. };
  65401. ArcFollowCamera.prototype._checkInputs = function () {
  65402. _super.prototype._checkInputs.call(this);
  65403. this.follow();
  65404. };
  65405. ArcFollowCamera.prototype.getClassName = function () {
  65406. return "ArcFollowCamera";
  65407. };
  65408. return ArcFollowCamera;
  65409. }(BABYLON.TargetCamera));
  65410. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65411. })(BABYLON || (BABYLON = {}));
  65412. //# sourceMappingURL=babylon.followCamera.js.map
  65413. var BABYLON;
  65414. (function (BABYLON) {
  65415. // We're mainly based on the logic defined into the FreeCamera code
  65416. var UniversalCamera = /** @class */ (function (_super) {
  65417. __extends(UniversalCamera, _super);
  65418. //-- end properties for backward compatibility for inputs
  65419. function UniversalCamera(name, position, scene) {
  65420. var _this = _super.call(this, name, position, scene) || this;
  65421. _this.inputs.addGamepad();
  65422. return _this;
  65423. }
  65424. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65425. //-- Begin properties for backward compatibility for inputs
  65426. get: function () {
  65427. var gamepad = this.inputs.attached["gamepad"];
  65428. if (gamepad)
  65429. return gamepad.gamepadAngularSensibility;
  65430. return 0;
  65431. },
  65432. set: function (value) {
  65433. var gamepad = this.inputs.attached["gamepad"];
  65434. if (gamepad)
  65435. gamepad.gamepadAngularSensibility = value;
  65436. },
  65437. enumerable: true,
  65438. configurable: true
  65439. });
  65440. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65441. get: function () {
  65442. var gamepad = this.inputs.attached["gamepad"];
  65443. if (gamepad)
  65444. return gamepad.gamepadMoveSensibility;
  65445. return 0;
  65446. },
  65447. set: function (value) {
  65448. var gamepad = this.inputs.attached["gamepad"];
  65449. if (gamepad)
  65450. gamepad.gamepadMoveSensibility = value;
  65451. },
  65452. enumerable: true,
  65453. configurable: true
  65454. });
  65455. UniversalCamera.prototype.getClassName = function () {
  65456. return "UniversalCamera";
  65457. };
  65458. return UniversalCamera;
  65459. }(BABYLON.TouchCamera));
  65460. BABYLON.UniversalCamera = UniversalCamera;
  65461. })(BABYLON || (BABYLON = {}));
  65462. //# sourceMappingURL=babylon.universalCamera.js.map
  65463. var BABYLON;
  65464. (function (BABYLON) {
  65465. // We're mainly based on the logic defined into the FreeCamera code
  65466. var GamepadCamera = /** @class */ (function (_super) {
  65467. __extends(GamepadCamera, _super);
  65468. //-- end properties for backward compatibility for inputs
  65469. function GamepadCamera(name, position, scene) {
  65470. return _super.call(this, name, position, scene) || this;
  65471. }
  65472. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65473. //-- Begin properties for backward compatibility for inputs
  65474. get: function () {
  65475. var gamepad = this.inputs.attached["gamepad"];
  65476. if (gamepad)
  65477. return gamepad.gamepadAngularSensibility;
  65478. return 0;
  65479. },
  65480. set: function (value) {
  65481. var gamepad = this.inputs.attached["gamepad"];
  65482. if (gamepad)
  65483. gamepad.gamepadAngularSensibility = value;
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65489. get: function () {
  65490. var gamepad = this.inputs.attached["gamepad"];
  65491. if (gamepad)
  65492. return gamepad.gamepadMoveSensibility;
  65493. return 0;
  65494. },
  65495. set: function (value) {
  65496. var gamepad = this.inputs.attached["gamepad"];
  65497. if (gamepad)
  65498. gamepad.gamepadMoveSensibility = value;
  65499. },
  65500. enumerable: true,
  65501. configurable: true
  65502. });
  65503. GamepadCamera.prototype.getClassName = function () {
  65504. return "GamepadCamera";
  65505. };
  65506. return GamepadCamera;
  65507. }(BABYLON.UniversalCamera));
  65508. BABYLON.GamepadCamera = GamepadCamera;
  65509. })(BABYLON || (BABYLON = {}));
  65510. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65511. var BABYLON;
  65512. (function (BABYLON) {
  65513. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65514. function PostProcessRenderPipelineManager() {
  65515. this._renderPipelines = {};
  65516. }
  65517. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65518. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65519. };
  65520. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65521. if (unique === void 0) { unique = false; }
  65522. var renderPipeline = this._renderPipelines[renderPipelineName];
  65523. if (!renderPipeline) {
  65524. return;
  65525. }
  65526. renderPipeline._attachCameras(cameras, unique);
  65527. };
  65528. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65529. var renderPipeline = this._renderPipelines[renderPipelineName];
  65530. if (!renderPipeline) {
  65531. return;
  65532. }
  65533. renderPipeline._detachCameras(cameras);
  65534. };
  65535. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65536. var renderPipeline = this._renderPipelines[renderPipelineName];
  65537. if (!renderPipeline) {
  65538. return;
  65539. }
  65540. renderPipeline._enableEffect(renderEffectName, cameras);
  65541. };
  65542. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65543. var renderPipeline = this._renderPipelines[renderPipelineName];
  65544. if (!renderPipeline) {
  65545. return;
  65546. }
  65547. renderPipeline._disableEffect(renderEffectName, cameras);
  65548. };
  65549. PostProcessRenderPipelineManager.prototype.update = function () {
  65550. for (var renderPipelineName in this._renderPipelines) {
  65551. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65552. var pipeline = this._renderPipelines[renderPipelineName];
  65553. if (!pipeline.isSupported) {
  65554. pipeline.dispose();
  65555. delete this._renderPipelines[renderPipelineName];
  65556. }
  65557. else {
  65558. pipeline._update();
  65559. }
  65560. }
  65561. }
  65562. };
  65563. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65564. for (var renderPipelineName in this._renderPipelines) {
  65565. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65566. var pipeline = this._renderPipelines[renderPipelineName];
  65567. pipeline._rebuild();
  65568. }
  65569. }
  65570. };
  65571. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65572. for (var renderPipelineName in this._renderPipelines) {
  65573. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65574. var pipeline = this._renderPipelines[renderPipelineName];
  65575. pipeline.dispose();
  65576. }
  65577. }
  65578. };
  65579. return PostProcessRenderPipelineManager;
  65580. }());
  65581. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65582. })(BABYLON || (BABYLON = {}));
  65583. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65584. var BABYLON;
  65585. (function (BABYLON) {
  65586. /**
  65587. * This represents a set of one or more post processes in Babylon.
  65588. * A post process can be used to apply a shader to a texture after it is rendered.
  65589. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65590. */
  65591. var PostProcessRenderEffect = /** @class */ (function () {
  65592. /**
  65593. * Instantiates a post process render effect.
  65594. * A post process can be used to apply a shader to a texture after it is rendered.
  65595. * @param engine The engine the effect is tied to
  65596. * @param name The name of the effect
  65597. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65598. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65599. */
  65600. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65601. this._name = name;
  65602. this._singleInstance = singleInstance || true;
  65603. this._getPostProcesses = getPostProcesses;
  65604. this._cameras = {};
  65605. this._indicesForCamera = {};
  65606. this._postProcesses = {};
  65607. }
  65608. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65609. /**
  65610. * Checks if all the post processes in the effect are supported.
  65611. */
  65612. get: function () {
  65613. for (var index in this._postProcesses) {
  65614. for (var ppIndex in this._postProcesses[index]) {
  65615. if (!this._postProcesses[index][ppIndex].isSupported) {
  65616. return false;
  65617. }
  65618. }
  65619. }
  65620. return true;
  65621. },
  65622. enumerable: true,
  65623. configurable: true
  65624. });
  65625. /**
  65626. * Updates the current state of the effect
  65627. */
  65628. PostProcessRenderEffect.prototype._update = function () {
  65629. };
  65630. /**
  65631. * Attaches the effect on cameras
  65632. * @param cameras The camera to attach to.
  65633. */
  65634. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65635. var _this = this;
  65636. var cameraKey;
  65637. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65638. if (!cams) {
  65639. return;
  65640. }
  65641. for (var i = 0; i < cams.length; i++) {
  65642. var camera = cams[i];
  65643. var cameraName = camera.name;
  65644. if (this._singleInstance) {
  65645. cameraKey = 0;
  65646. }
  65647. else {
  65648. cameraKey = cameraName;
  65649. }
  65650. if (!this._postProcesses[cameraKey]) {
  65651. var postProcess = this._getPostProcesses();
  65652. if (postProcess) {
  65653. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65654. }
  65655. }
  65656. if (!this._indicesForCamera[cameraName]) {
  65657. this._indicesForCamera[cameraName] = [];
  65658. }
  65659. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65660. var index = camera.attachPostProcess(postProcess);
  65661. _this._indicesForCamera[cameraName].push(index);
  65662. });
  65663. if (!this._cameras[cameraName]) {
  65664. this._cameras[cameraName] = camera;
  65665. }
  65666. }
  65667. };
  65668. /**
  65669. * Detatches the effect on cameras
  65670. * @param cameras The camera to detatch from.
  65671. */
  65672. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65673. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65674. if (!cams) {
  65675. return;
  65676. }
  65677. for (var i = 0; i < cams.length; i++) {
  65678. var camera = cams[i];
  65679. var cameraName = camera.name;
  65680. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65681. camera.detachPostProcess(postProcess);
  65682. });
  65683. if (this._cameras[cameraName]) {
  65684. //this._indicesForCamera.splice(index, 1);
  65685. this._cameras[cameraName] = null;
  65686. }
  65687. }
  65688. };
  65689. /**
  65690. * Enables the effect on given cameras
  65691. * @param cameras The camera to enable.
  65692. */
  65693. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65694. var _this = this;
  65695. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65696. if (!cams) {
  65697. return;
  65698. }
  65699. for (var i = 0; i < cams.length; i++) {
  65700. var camera = cams[i];
  65701. var cameraName = camera.name;
  65702. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65703. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65704. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65705. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65706. });
  65707. }
  65708. }
  65709. }
  65710. };
  65711. /**
  65712. * Disables the effect on the given cameras
  65713. * @param cameras The camera to disable.
  65714. */
  65715. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65716. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65717. if (!cams) {
  65718. return;
  65719. }
  65720. for (var i = 0; i < cams.length; i++) {
  65721. var camera = cams[i];
  65722. var cameraName = camera.name;
  65723. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65724. camera.detachPostProcess(postProcess);
  65725. });
  65726. }
  65727. };
  65728. /**
  65729. * Gets a list of the post processes contained in the effect.
  65730. * @param camera The camera to get the post processes on.
  65731. * @returns The list of the post processes in the effect.
  65732. */
  65733. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65734. if (this._singleInstance) {
  65735. return this._postProcesses[0];
  65736. }
  65737. else {
  65738. if (!camera) {
  65739. return null;
  65740. }
  65741. return this._postProcesses[camera.name];
  65742. }
  65743. };
  65744. return PostProcessRenderEffect;
  65745. }());
  65746. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65747. })(BABYLON || (BABYLON = {}));
  65748. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65749. var BABYLON;
  65750. (function (BABYLON) {
  65751. var PostProcessRenderPipeline = /** @class */ (function () {
  65752. function PostProcessRenderPipeline(engine, name) {
  65753. this.engine = engine;
  65754. this._name = name;
  65755. this._renderEffects = {};
  65756. this._renderEffectsForIsolatedPass = new Array();
  65757. this._cameras = [];
  65758. }
  65759. PostProcessRenderPipeline.prototype.getClassName = function () {
  65760. return "PostProcessRenderPipeline";
  65761. };
  65762. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65763. get: function () {
  65764. for (var renderEffectName in this._renderEffects) {
  65765. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65766. if (!this._renderEffects[renderEffectName].isSupported) {
  65767. return false;
  65768. }
  65769. }
  65770. }
  65771. return true;
  65772. },
  65773. enumerable: true,
  65774. configurable: true
  65775. });
  65776. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65777. this._renderEffects[renderEffect._name] = renderEffect;
  65778. };
  65779. // private
  65780. PostProcessRenderPipeline.prototype._rebuild = function () {
  65781. };
  65782. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65783. var renderEffects = this._renderEffects[renderEffectName];
  65784. if (!renderEffects) {
  65785. return;
  65786. }
  65787. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65788. };
  65789. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65790. var renderEffects = this._renderEffects[renderEffectName];
  65791. if (!renderEffects) {
  65792. return;
  65793. }
  65794. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65795. };
  65796. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65797. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65798. if (!cams) {
  65799. return;
  65800. }
  65801. var indicesToDelete = [];
  65802. var i;
  65803. for (i = 0; i < cams.length; i++) {
  65804. var camera = cams[i];
  65805. var cameraName = camera.name;
  65806. if (this._cameras.indexOf(camera) === -1) {
  65807. this._cameras[cameraName] = camera;
  65808. }
  65809. else if (unique) {
  65810. indicesToDelete.push(i);
  65811. }
  65812. }
  65813. for (i = 0; i < indicesToDelete.length; i++) {
  65814. cameras.splice(indicesToDelete[i], 1);
  65815. }
  65816. for (var renderEffectName in this._renderEffects) {
  65817. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65818. this._renderEffects[renderEffectName]._attachCameras(cams);
  65819. }
  65820. }
  65821. };
  65822. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65823. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65824. if (!cams) {
  65825. return;
  65826. }
  65827. for (var renderEffectName in this._renderEffects) {
  65828. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65829. this._renderEffects[renderEffectName]._detachCameras(cams);
  65830. }
  65831. }
  65832. for (var i = 0; i < cams.length; i++) {
  65833. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65834. }
  65835. };
  65836. PostProcessRenderPipeline.prototype._update = function () {
  65837. for (var renderEffectName in this._renderEffects) {
  65838. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65839. this._renderEffects[renderEffectName]._update();
  65840. }
  65841. }
  65842. for (var i = 0; i < this._cameras.length; i++) {
  65843. var cameraName = this._cameras[i].name;
  65844. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65845. this._renderEffectsForIsolatedPass[cameraName]._update();
  65846. }
  65847. }
  65848. };
  65849. PostProcessRenderPipeline.prototype._reset = function () {
  65850. this._renderEffects = {};
  65851. this._renderEffectsForIsolatedPass = new Array();
  65852. };
  65853. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65854. // 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)
  65855. var effectKeys = Object.keys(this._renderEffects);
  65856. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65857. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65858. if (postProcesses) {
  65859. postProcesses[0].samples = 4;
  65860. return true;
  65861. }
  65862. }
  65863. return false;
  65864. };
  65865. PostProcessRenderPipeline.prototype.dispose = function () {
  65866. // Must be implemented by children
  65867. };
  65868. __decorate([
  65869. BABYLON.serialize()
  65870. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65871. return PostProcessRenderPipeline;
  65872. }());
  65873. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65874. })(BABYLON || (BABYLON = {}));
  65875. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65876. var BABYLON;
  65877. (function (BABYLON) {
  65878. /**
  65879. * This represents a depth renderer in Babylon.
  65880. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65881. */
  65882. var DepthRenderer = /** @class */ (function () {
  65883. /**
  65884. * Instantiates a depth renderer
  65885. * @param scene The scene the renderer belongs to
  65886. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65887. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65888. */
  65889. function DepthRenderer(scene, type, camera) {
  65890. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65891. if (camera === void 0) { camera = null; }
  65892. var _this = this;
  65893. this._scene = scene;
  65894. this._camera = camera;
  65895. var engine = scene.getEngine();
  65896. // Render target
  65897. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65898. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65899. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65900. this._depthMap.refreshRate = 1;
  65901. this._depthMap.renderParticles = false;
  65902. this._depthMap.renderList = null;
  65903. // Camera to get depth map from to support multiple concurrent cameras
  65904. this._depthMap.activeCamera = this._camera;
  65905. this._depthMap.ignoreCameraViewport = true;
  65906. this._depthMap.useCameraPostProcesses = false;
  65907. // set default depth value to 1.0 (far away)
  65908. this._depthMap.onClearObservable.add(function (engine) {
  65909. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65910. });
  65911. // Custom render function
  65912. var renderSubMesh = function (subMesh) {
  65913. var mesh = subMesh.getRenderingMesh();
  65914. var scene = _this._scene;
  65915. var engine = scene.getEngine();
  65916. var material = subMesh.getMaterial();
  65917. if (!material) {
  65918. return;
  65919. }
  65920. // Culling and reverse (right handed system)
  65921. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65922. // Managing instances
  65923. var batch = mesh._getInstancesRenderList(subMesh._id);
  65924. if (batch.mustReturn) {
  65925. return;
  65926. }
  65927. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65928. var camera = _this._camera || scene.activeCamera;
  65929. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65930. engine.enableEffect(_this._effect);
  65931. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65932. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65933. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65934. // Alpha test
  65935. if (material && material.needAlphaTesting()) {
  65936. var alphaTexture = material.getAlphaTestTexture();
  65937. if (alphaTexture) {
  65938. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65939. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65940. }
  65941. }
  65942. // Bones
  65943. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65944. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65945. }
  65946. // Draw
  65947. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65948. }
  65949. };
  65950. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65951. var index;
  65952. if (depthOnlySubMeshes.length) {
  65953. engine.setColorWrite(false);
  65954. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65955. renderSubMesh(depthOnlySubMeshes.data[index]);
  65956. }
  65957. engine.setColorWrite(true);
  65958. }
  65959. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65960. renderSubMesh(opaqueSubMeshes.data[index]);
  65961. }
  65962. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65963. renderSubMesh(alphaTestSubMeshes.data[index]);
  65964. }
  65965. };
  65966. }
  65967. /**
  65968. * Creates the depth rendering effect and checks if the effect is ready.
  65969. * @param subMesh The submesh to be used to render the depth map of
  65970. * @param useInstances If multiple world instances should be used
  65971. * @returns if the depth renderer is ready to render the depth map
  65972. */
  65973. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65974. var material = subMesh.getMaterial();
  65975. if (material.disableDepthWrite) {
  65976. return false;
  65977. }
  65978. var defines = [];
  65979. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65980. var mesh = subMesh.getMesh();
  65981. // Alpha test
  65982. if (material && material.needAlphaTesting()) {
  65983. defines.push("#define ALPHATEST");
  65984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65985. attribs.push(BABYLON.VertexBuffer.UVKind);
  65986. defines.push("#define UV1");
  65987. }
  65988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65989. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65990. defines.push("#define UV2");
  65991. }
  65992. }
  65993. // Bones
  65994. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65995. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65996. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65997. if (mesh.numBoneInfluencers > 4) {
  65998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66000. }
  66001. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66002. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66003. }
  66004. else {
  66005. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66006. }
  66007. // Instances
  66008. if (useInstances) {
  66009. defines.push("#define INSTANCES");
  66010. attribs.push("world0");
  66011. attribs.push("world1");
  66012. attribs.push("world2");
  66013. attribs.push("world3");
  66014. }
  66015. // Get correct effect
  66016. var join = defines.join("\n");
  66017. if (this._cachedDefines !== join) {
  66018. this._cachedDefines = join;
  66019. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66020. }
  66021. return this._effect.isReady();
  66022. };
  66023. /**
  66024. * Gets the texture which the depth map will be written to.
  66025. * @returns The depth map texture
  66026. */
  66027. DepthRenderer.prototype.getDepthMap = function () {
  66028. return this._depthMap;
  66029. };
  66030. /**
  66031. * Disposes of the depth renderer.
  66032. */
  66033. DepthRenderer.prototype.dispose = function () {
  66034. this._depthMap.dispose();
  66035. };
  66036. return DepthRenderer;
  66037. }());
  66038. BABYLON.DepthRenderer = DepthRenderer;
  66039. })(BABYLON || (BABYLON = {}));
  66040. //# sourceMappingURL=babylon.depthRenderer.js.map
  66041. var BABYLON;
  66042. (function (BABYLON) {
  66043. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66044. __extends(SSAORenderingPipeline, _super);
  66045. /**
  66046. * @constructor
  66047. * @param {string} name - The rendering pipeline name
  66048. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66049. * @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 }
  66050. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66051. */
  66052. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66053. var _this = _super.call(this, scene.getEngine(), name) || this;
  66054. // Members
  66055. /**
  66056. * The PassPostProcess id in the pipeline that contains the original scene color
  66057. * @type {string}
  66058. */
  66059. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66060. /**
  66061. * The SSAO PostProcess id in the pipeline
  66062. * @type {string}
  66063. */
  66064. _this.SSAORenderEffect = "SSAORenderEffect";
  66065. /**
  66066. * The horizontal blur PostProcess id in the pipeline
  66067. * @type {string}
  66068. */
  66069. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66070. /**
  66071. * The vertical blur PostProcess id in the pipeline
  66072. * @type {string}
  66073. */
  66074. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66075. /**
  66076. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66077. * @type {string}
  66078. */
  66079. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66080. /**
  66081. * The output strength of the SSAO post-process. Default value is 1.0.
  66082. * @type {number}
  66083. */
  66084. _this.totalStrength = 1.0;
  66085. /**
  66086. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66087. * @type {number}
  66088. */
  66089. _this.radius = 0.0001;
  66090. /**
  66091. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66092. * Must not be equal to fallOff and superior to fallOff.
  66093. * Default value is 0.975
  66094. * @type {number}
  66095. */
  66096. _this.area = 0.0075;
  66097. /**
  66098. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66099. * Must not be equal to area and inferior to area.
  66100. * Default value is 0.0
  66101. * @type {number}
  66102. */
  66103. _this.fallOff = 0.000001;
  66104. /**
  66105. * The base color of the SSAO post-process
  66106. * The final result is "base + ssao" between [0, 1]
  66107. * @type {number}
  66108. */
  66109. _this.base = 0.5;
  66110. _this._firstUpdate = true;
  66111. _this._scene = scene;
  66112. // Set up assets
  66113. _this._createRandomTexture();
  66114. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66115. var ssaoRatio = ratio.ssaoRatio || ratio;
  66116. var combineRatio = ratio.combineRatio || ratio;
  66117. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66118. _this._createSSAOPostProcess(ssaoRatio);
  66119. _this._createBlurPostProcess(ssaoRatio);
  66120. _this._createSSAOCombinePostProcess(combineRatio);
  66121. // Set up pipeline
  66122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66127. // Finish
  66128. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66129. if (cameras)
  66130. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66131. return _this;
  66132. }
  66133. // Public Methods
  66134. /**
  66135. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66136. */
  66137. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66138. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66139. for (var i = 0; i < this._scene.cameras.length; i++) {
  66140. var camera = this._scene.cameras[i];
  66141. this._originalColorPostProcess.dispose(camera);
  66142. this._ssaoPostProcess.dispose(camera);
  66143. this._blurHPostProcess.dispose(camera);
  66144. this._blurVPostProcess.dispose(camera);
  66145. this._ssaoCombinePostProcess.dispose(camera);
  66146. }
  66147. this._randomTexture.dispose();
  66148. if (disableDepthRender)
  66149. this._scene.disableDepthRenderer();
  66150. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66151. _super.prototype.dispose.call(this);
  66152. };
  66153. // Private Methods
  66154. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66155. var _this = this;
  66156. var size = 16;
  66157. 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);
  66158. 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);
  66159. this._blurHPostProcess.onActivateObservable.add(function () {
  66160. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66161. _this._blurHPostProcess.kernel = size * dw;
  66162. });
  66163. this._blurVPostProcess.onActivateObservable.add(function () {
  66164. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66165. _this._blurVPostProcess.kernel = size * dw;
  66166. });
  66167. };
  66168. SSAORenderingPipeline.prototype._rebuild = function () {
  66169. this._firstUpdate = true;
  66170. _super.prototype._rebuild.call(this);
  66171. };
  66172. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66173. var _this = this;
  66174. var numSamples = 16;
  66175. var sampleSphere = [
  66176. 0.5381, 0.1856, -0.4319,
  66177. 0.1379, 0.2486, 0.4430,
  66178. 0.3371, 0.5679, -0.0057,
  66179. -0.6999, -0.0451, -0.0019,
  66180. 0.0689, -0.1598, -0.8547,
  66181. 0.0560, 0.0069, -0.1843,
  66182. -0.0146, 0.1402, 0.0762,
  66183. 0.0100, -0.1924, -0.0344,
  66184. -0.3577, -0.5301, -0.4358,
  66185. -0.3169, 0.1063, 0.0158,
  66186. 0.0103, -0.5869, 0.0046,
  66187. -0.0897, -0.4940, 0.3287,
  66188. 0.7119, -0.0154, -0.0918,
  66189. -0.0533, 0.0596, -0.5411,
  66190. 0.0352, -0.0631, 0.5460,
  66191. -0.4776, 0.2847, -0.0271
  66192. ];
  66193. var samplesFactor = 1.0 / numSamples;
  66194. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66195. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66196. "area", "fallOff", "base", "range", "viewport"
  66197. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66198. this._ssaoPostProcess.onApply = function (effect) {
  66199. if (_this._firstUpdate) {
  66200. effect.setArray3("sampleSphere", sampleSphere);
  66201. effect.setFloat("samplesFactor", samplesFactor);
  66202. effect.setFloat("randTextureTiles", 4.0);
  66203. }
  66204. effect.setFloat("totalStrength", _this.totalStrength);
  66205. effect.setFloat("radius", _this.radius);
  66206. effect.setFloat("area", _this.area);
  66207. effect.setFloat("fallOff", _this.fallOff);
  66208. effect.setFloat("base", _this.base);
  66209. effect.setTexture("textureSampler", _this._depthTexture);
  66210. effect.setTexture("randomSampler", _this._randomTexture);
  66211. };
  66212. };
  66213. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66214. var _this = this;
  66215. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66216. this._ssaoCombinePostProcess.onApply = function (effect) {
  66217. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66218. };
  66219. };
  66220. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66221. var size = 512;
  66222. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66223. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66224. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66225. var context = this._randomTexture.getContext();
  66226. var rand = function (min, max) {
  66227. return Math.random() * (max - min) + min;
  66228. };
  66229. var randVector = BABYLON.Vector3.Zero();
  66230. for (var x = 0; x < size; x++) {
  66231. for (var y = 0; y < size; y++) {
  66232. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66233. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66234. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66235. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66236. context.fillRect(x, y, 1, 1);
  66237. }
  66238. }
  66239. this._randomTexture.update(false);
  66240. };
  66241. __decorate([
  66242. BABYLON.serialize()
  66243. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66244. __decorate([
  66245. BABYLON.serialize()
  66246. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66247. __decorate([
  66248. BABYLON.serialize()
  66249. ], SSAORenderingPipeline.prototype, "area", void 0);
  66250. __decorate([
  66251. BABYLON.serialize()
  66252. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66253. __decorate([
  66254. BABYLON.serialize()
  66255. ], SSAORenderingPipeline.prototype, "base", void 0);
  66256. return SSAORenderingPipeline;
  66257. }(BABYLON.PostProcessRenderPipeline));
  66258. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66259. })(BABYLON || (BABYLON = {}));
  66260. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66261. var BABYLON;
  66262. (function (BABYLON) {
  66263. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66264. __extends(SSAO2RenderingPipeline, _super);
  66265. /**
  66266. * @constructor
  66267. * @param {string} name - The rendering pipeline name
  66268. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66269. * @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 }
  66270. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66271. */
  66272. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66273. var _this = _super.call(this, scene.getEngine(), name) || this;
  66274. // Members
  66275. /**
  66276. * The PassPostProcess id in the pipeline that contains the original scene color
  66277. * @type {string}
  66278. */
  66279. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66280. /**
  66281. * The SSAO PostProcess id in the pipeline
  66282. * @type {string}
  66283. */
  66284. _this.SSAORenderEffect = "SSAORenderEffect";
  66285. /**
  66286. * The horizontal blur PostProcess id in the pipeline
  66287. * @type {string}
  66288. */
  66289. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66290. /**
  66291. * The vertical blur PostProcess id in the pipeline
  66292. * @type {string}
  66293. */
  66294. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66295. /**
  66296. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66297. * @type {string}
  66298. */
  66299. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66300. /**
  66301. * The output strength of the SSAO post-process. Default value is 1.0.
  66302. * @type {number}
  66303. */
  66304. _this.totalStrength = 1.0;
  66305. /**
  66306. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66307. * @type {number}
  66308. */
  66309. _this.maxZ = 100.0;
  66310. /**
  66311. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66312. * @type {number}
  66313. */
  66314. _this.minZAspect = 0.2;
  66315. /**
  66316. * Number of samples used for the SSAO calculations. Default value is 8
  66317. * @type {number}
  66318. */
  66319. _this._samples = 8;
  66320. /**
  66321. * Are we using bilateral blur ?
  66322. * @type {boolean}
  66323. */
  66324. _this._expensiveBlur = true;
  66325. /**
  66326. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66327. * @type {number}
  66328. */
  66329. _this.radius = 2.0;
  66330. /**
  66331. * The base color of the SSAO post-process
  66332. * The final result is "base + ssao" between [0, 1]
  66333. * @type {number}
  66334. */
  66335. _this.base = 0.1;
  66336. _this._firstUpdate = true;
  66337. _this._scene = scene;
  66338. if (!_this.isSupported) {
  66339. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66340. return _this;
  66341. }
  66342. var ssaoRatio = ratio.ssaoRatio || ratio;
  66343. var blurRatio = ratio.blurRatio || ratio;
  66344. // Set up assets
  66345. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66346. _this._createRandomTexture();
  66347. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66348. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66349. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66350. _this._createSSAOPostProcess(1.0);
  66351. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66352. _this._createSSAOCombinePostProcess(blurRatio);
  66353. // Set up pipeline
  66354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66359. // Finish
  66360. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66361. if (cameras)
  66362. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66363. return _this;
  66364. }
  66365. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66366. get: function () {
  66367. return this._samples;
  66368. },
  66369. set: function (n) {
  66370. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66371. this._samples = n;
  66372. this._sampleSphere = this._generateHemisphere();
  66373. this._firstUpdate = true;
  66374. },
  66375. enumerable: true,
  66376. configurable: true
  66377. });
  66378. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66379. get: function () {
  66380. return this._expensiveBlur;
  66381. },
  66382. set: function (b) {
  66383. 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"]);
  66384. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66385. this._expensiveBlur = b;
  66386. this._firstUpdate = true;
  66387. },
  66388. enumerable: true,
  66389. configurable: true
  66390. });
  66391. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66392. /**
  66393. * Support test.
  66394. * @type {boolean}
  66395. */
  66396. get: function () {
  66397. var engine = BABYLON.Engine.LastCreatedEngine;
  66398. if (!engine) {
  66399. return false;
  66400. }
  66401. return engine.getCaps().drawBuffersExtension;
  66402. },
  66403. enumerable: true,
  66404. configurable: true
  66405. });
  66406. // Public Methods
  66407. /**
  66408. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66409. */
  66410. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66411. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66412. for (var i = 0; i < this._scene.cameras.length; i++) {
  66413. var camera = this._scene.cameras[i];
  66414. this._originalColorPostProcess.dispose(camera);
  66415. this._ssaoPostProcess.dispose(camera);
  66416. this._blurHPostProcess.dispose(camera);
  66417. this._blurVPostProcess.dispose(camera);
  66418. this._ssaoCombinePostProcess.dispose(camera);
  66419. }
  66420. this._randomTexture.dispose();
  66421. if (disableGeometryBufferRenderer)
  66422. this._scene.disableGeometryBufferRenderer();
  66423. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66424. _super.prototype.dispose.call(this);
  66425. };
  66426. // Private Methods
  66427. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66428. var _this = this;
  66429. this._samplerOffsets = [];
  66430. var expensive = this.expensiveBlur;
  66431. for (var i = -8; i < 8; i++) {
  66432. this._samplerOffsets.push(i * 2 + 0.5);
  66433. }
  66434. 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");
  66435. this._blurHPostProcess.onApply = function (effect) {
  66436. if (!_this._scene.activeCamera) {
  66437. return;
  66438. }
  66439. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66440. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66441. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66442. effect.setFloat("radius", _this.radius);
  66443. effect.setTexture("depthSampler", _this._depthTexture);
  66444. if (_this._firstUpdate) {
  66445. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66446. }
  66447. };
  66448. 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");
  66449. this._blurVPostProcess.onApply = function (effect) {
  66450. if (!_this._scene.activeCamera) {
  66451. return;
  66452. }
  66453. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66454. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66455. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66456. effect.setFloat("radius", _this.radius);
  66457. effect.setTexture("depthSampler", _this._depthTexture);
  66458. if (_this._firstUpdate) {
  66459. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66460. _this._firstUpdate = false;
  66461. }
  66462. };
  66463. };
  66464. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66465. this._firstUpdate = true;
  66466. _super.prototype._rebuild.call(this);
  66467. };
  66468. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66469. var numSamples = this.samples;
  66470. var result = [];
  66471. var vector, scale;
  66472. var rand = function (min, max) {
  66473. return Math.random() * (max - min) + min;
  66474. };
  66475. var i = 0;
  66476. while (i < numSamples) {
  66477. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66478. vector.normalize();
  66479. scale = i / numSamples;
  66480. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66481. vector.scaleInPlace(scale);
  66482. result.push(vector.x, vector.y, vector.z);
  66483. i++;
  66484. }
  66485. return result;
  66486. };
  66487. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66488. var _this = this;
  66489. var numSamples = this.samples;
  66490. this._sampleSphere = this._generateHemisphere();
  66491. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66492. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66493. "base", "range", "projection", "near", "far", "texelSize",
  66494. "xViewport", "yViewport", "maxZ", "minZAspect"
  66495. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66496. this._ssaoPostProcess.onApply = function (effect) {
  66497. if (_this._firstUpdate) {
  66498. effect.setArray3("sampleSphere", _this._sampleSphere);
  66499. effect.setFloat("randTextureTiles", 4.0);
  66500. }
  66501. if (!_this._scene.activeCamera) {
  66502. return;
  66503. }
  66504. effect.setFloat("samplesFactor", 1 / _this.samples);
  66505. effect.setFloat("totalStrength", _this.totalStrength);
  66506. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66507. effect.setFloat("radius", _this.radius);
  66508. effect.setFloat("maxZ", _this.maxZ);
  66509. effect.setFloat("minZAspect", _this.minZAspect);
  66510. effect.setFloat("base", _this.base);
  66511. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66512. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66513. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66514. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66515. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66516. effect.setTexture("textureSampler", _this._depthTexture);
  66517. effect.setTexture("normalSampler", _this._normalTexture);
  66518. effect.setTexture("randomSampler", _this._randomTexture);
  66519. };
  66520. };
  66521. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66522. var _this = this;
  66523. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66524. this._ssaoCombinePostProcess.onApply = function (effect) {
  66525. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66526. };
  66527. };
  66528. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66529. var size = 512;
  66530. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66531. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66532. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66533. var context = this._randomTexture.getContext();
  66534. var rand = function (min, max) {
  66535. return Math.random() * (max - min) + min;
  66536. };
  66537. var randVector = BABYLON.Vector3.Zero();
  66538. for (var x = 0; x < size; x++) {
  66539. for (var y = 0; y < size; y++) {
  66540. randVector.x = rand(0.0, 1.0);
  66541. randVector.y = rand(0.0, 1.0);
  66542. randVector.z = 0.0;
  66543. randVector.normalize();
  66544. randVector.scaleInPlace(255);
  66545. randVector.x = Math.floor(randVector.x);
  66546. randVector.y = Math.floor(randVector.y);
  66547. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66548. context.fillRect(x, y, 1, 1);
  66549. }
  66550. }
  66551. this._randomTexture.update(false);
  66552. };
  66553. __decorate([
  66554. BABYLON.serialize()
  66555. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66556. __decorate([
  66557. BABYLON.serialize()
  66558. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66559. __decorate([
  66560. BABYLON.serialize()
  66561. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66562. __decorate([
  66563. BABYLON.serialize("samples")
  66564. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66565. __decorate([
  66566. BABYLON.serialize("expensiveBlur")
  66567. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66568. __decorate([
  66569. BABYLON.serialize()
  66570. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66571. __decorate([
  66572. BABYLON.serialize()
  66573. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66574. return SSAO2RenderingPipeline;
  66575. }(BABYLON.PostProcessRenderPipeline));
  66576. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66577. })(BABYLON || (BABYLON = {}));
  66578. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66579. // BABYLON.JS Chromatic Aberration GLSL Shader
  66580. // Author: Olivier Guyot
  66581. // Separates very slightly R, G and B colors on the edges of the screen
  66582. // Inspired by Francois Tarlier & Martins Upitis
  66583. var BABYLON;
  66584. (function (BABYLON) {
  66585. var LensRenderingPipeline = /** @class */ (function (_super) {
  66586. __extends(LensRenderingPipeline, _super);
  66587. /**
  66588. * @constructor
  66589. *
  66590. * Effect parameters are as follow:
  66591. * {
  66592. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66593. * edge_blur: number; // from 0 to x (1 for realism)
  66594. * distortion: number; // from 0 to x (1 for realism)
  66595. * grain_amount: number; // from 0 to 1
  66596. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66597. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66598. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66599. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66600. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66601. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66602. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66603. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66604. * }
  66605. * Note: if an effect parameter is unset, effect is disabled
  66606. *
  66607. * @param {string} name - The rendering pipeline name
  66608. * @param {object} parameters - An object containing all parameters (see above)
  66609. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66610. * @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)
  66611. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66612. */
  66613. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66614. if (ratio === void 0) { ratio = 1.0; }
  66615. var _this = _super.call(this, scene.getEngine(), name) || this;
  66616. // Lens effects can be of the following:
  66617. // - chromatic aberration (slight shift of RGB colors)
  66618. // - blur on the edge of the lens
  66619. // - lens distortion
  66620. // - depth-of-field blur & highlights enhancing
  66621. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66622. // - grain effect (noise or custom texture)
  66623. // Two additional texture samplers are needed:
  66624. // - depth map (for depth-of-field)
  66625. // - grain texture
  66626. /**
  66627. * The chromatic aberration PostProcess id in the pipeline
  66628. * @type {string}
  66629. */
  66630. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66631. /**
  66632. * The highlights enhancing PostProcess id in the pipeline
  66633. * @type {string}
  66634. */
  66635. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66636. /**
  66637. * The depth-of-field PostProcess id in the pipeline
  66638. * @type {string}
  66639. */
  66640. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66641. _this._scene = scene;
  66642. // Fetch texture samplers
  66643. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66644. if (parameters.grain_texture) {
  66645. _this._grainTexture = parameters.grain_texture;
  66646. }
  66647. else {
  66648. _this._createGrainTexture();
  66649. }
  66650. // save parameters
  66651. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66652. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66653. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66654. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66655. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66656. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66657. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66658. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66659. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66660. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66661. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66662. // Create effects
  66663. _this._createChromaticAberrationPostProcess(ratio);
  66664. _this._createHighlightsPostProcess(ratio);
  66665. _this._createDepthOfFieldPostProcess(ratio / 4);
  66666. // Set up pipeline
  66667. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66668. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66669. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66670. if (_this._highlightsGain === -1) {
  66671. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66672. }
  66673. // Finish
  66674. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66675. if (cameras) {
  66676. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66677. }
  66678. return _this;
  66679. }
  66680. // public methods (self explanatory)
  66681. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66682. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66683. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66684. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66685. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66686. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66687. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66688. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66689. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66690. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66691. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66692. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66693. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66694. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66695. };
  66696. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66697. this._highlightsPostProcess.updateEffect();
  66698. };
  66699. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66700. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66701. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66702. this._highlightsGain = amount;
  66703. };
  66704. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66705. if (this._highlightsGain === -1) {
  66706. this._highlightsGain = 1.0;
  66707. }
  66708. this._highlightsThreshold = amount;
  66709. };
  66710. LensRenderingPipeline.prototype.disableHighlights = function () {
  66711. this._highlightsGain = -1;
  66712. };
  66713. /**
  66714. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66715. */
  66716. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66717. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66718. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66719. this._chromaticAberrationPostProcess = null;
  66720. this._highlightsPostProcess = null;
  66721. this._depthOfFieldPostProcess = null;
  66722. this._grainTexture.dispose();
  66723. if (disableDepthRender)
  66724. this._scene.disableDepthRenderer();
  66725. };
  66726. // colors shifting and distortion
  66727. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66728. var _this = this;
  66729. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  66730. [], // samplers
  66731. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66732. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66733. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66734. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66735. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66736. effect.setFloat('radialIntensity', 1);
  66737. effect.setFloat2('direction', 17, 17);
  66738. effect.setFloat2('centerPosition', 0.5, 0.5);
  66739. };
  66740. };
  66741. // highlights enhancing
  66742. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66743. var _this = this;
  66744. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66745. [], // samplers
  66746. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66747. this._highlightsPostProcess.onApply = function (effect) {
  66748. effect.setFloat('gain', _this._highlightsGain);
  66749. effect.setFloat('threshold', _this._highlightsThreshold);
  66750. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66751. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66752. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66753. };
  66754. };
  66755. // colors shifting and distortion
  66756. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66757. var _this = this;
  66758. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66759. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66760. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66761. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66762. this._depthOfFieldPostProcess.onApply = function (effect) {
  66763. effect.setTexture("depthSampler", _this._depthTexture);
  66764. effect.setTexture("grainSampler", _this._grainTexture);
  66765. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66766. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66767. effect.setFloat('grain_amount', _this._grainAmount);
  66768. effect.setBool('blur_noise', _this._blurNoise);
  66769. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66770. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66771. effect.setFloat('distortion', _this._distortion);
  66772. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66773. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66774. effect.setFloat('aperture', _this._dofAperture);
  66775. effect.setFloat('darken', _this._dofDarken);
  66776. effect.setFloat('edge_blur', _this._edgeBlur);
  66777. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66778. if (_this._scene.activeCamera) {
  66779. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66780. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66781. }
  66782. };
  66783. };
  66784. // creates a black and white random noise texture, 512x512
  66785. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66786. var size = 512;
  66787. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66788. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66789. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66790. var context = this._grainTexture.getContext();
  66791. var rand = function (min, max) {
  66792. return Math.random() * (max - min) + min;
  66793. };
  66794. var value;
  66795. for (var x = 0; x < size; x++) {
  66796. for (var y = 0; y < size; y++) {
  66797. value = Math.floor(rand(0.42, 0.58) * 255);
  66798. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66799. context.fillRect(x, y, 1, 1);
  66800. }
  66801. }
  66802. this._grainTexture.update(false);
  66803. };
  66804. return LensRenderingPipeline;
  66805. }(BABYLON.PostProcessRenderPipeline));
  66806. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66807. })(BABYLON || (BABYLON = {}));
  66808. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66809. var BABYLON;
  66810. (function (BABYLON) {
  66811. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66812. __extends(StandardRenderingPipeline, _super);
  66813. /**
  66814. * @constructor
  66815. * @param {string} name - The rendering pipeline name
  66816. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66817. * @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)
  66818. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66819. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66820. */
  66821. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66822. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66823. var _this = _super.call(this, scene.getEngine(), name) || this;
  66824. _this.downSampleX4PostProcess = null;
  66825. _this.brightPassPostProcess = null;
  66826. _this.blurHPostProcesses = [];
  66827. _this.blurVPostProcesses = [];
  66828. _this.textureAdderPostProcess = null;
  66829. _this.volumetricLightPostProcess = null;
  66830. _this.volumetricLightSmoothXPostProcess = null;
  66831. _this.volumetricLightSmoothYPostProcess = null;
  66832. _this.volumetricLightMergePostProces = null;
  66833. _this.volumetricLightFinalPostProcess = null;
  66834. _this.luminancePostProcess = null;
  66835. _this.luminanceDownSamplePostProcesses = [];
  66836. _this.hdrPostProcess = null;
  66837. _this.textureAdderFinalPostProcess = null;
  66838. _this.lensFlareFinalPostProcess = null;
  66839. _this.hdrFinalPostProcess = null;
  66840. _this.lensFlarePostProcess = null;
  66841. _this.lensFlareComposePostProcess = null;
  66842. _this.motionBlurPostProcess = null;
  66843. _this.depthOfFieldPostProcess = null;
  66844. // Values
  66845. _this.brightThreshold = 1.0;
  66846. _this.blurWidth = 512.0;
  66847. _this.horizontalBlur = false;
  66848. _this.exposure = 1.0;
  66849. _this.lensTexture = null;
  66850. _this.volumetricLightCoefficient = 0.2;
  66851. _this.volumetricLightPower = 4.0;
  66852. _this.volumetricLightBlurScale = 64.0;
  66853. _this.sourceLight = null;
  66854. _this.hdrMinimumLuminance = 1.0;
  66855. _this.hdrDecreaseRate = 0.5;
  66856. _this.hdrIncreaseRate = 0.5;
  66857. _this.lensColorTexture = null;
  66858. _this.lensFlareStrength = 20.0;
  66859. _this.lensFlareGhostDispersal = 1.4;
  66860. _this.lensFlareHaloWidth = 0.7;
  66861. _this.lensFlareDistortionStrength = 16.0;
  66862. _this.lensStarTexture = null;
  66863. _this.lensFlareDirtTexture = null;
  66864. _this.depthOfFieldDistance = 10.0;
  66865. _this.depthOfFieldBlurWidth = 64.0;
  66866. _this.motionStrength = 1.0;
  66867. // IAnimatable
  66868. _this.animations = [];
  66869. _this._currentDepthOfFieldSource = null;
  66870. _this._hdrCurrentLuminance = 1.0;
  66871. // Getters and setters
  66872. _this._bloomEnabled = true;
  66873. _this._depthOfFieldEnabled = false;
  66874. _this._vlsEnabled = false;
  66875. _this._lensFlareEnabled = false;
  66876. _this._hdrEnabled = false;
  66877. _this._motionBlurEnabled = false;
  66878. _this._motionBlurSamples = 64.0;
  66879. _this._volumetricLightStepsCount = 50.0;
  66880. _this._cameras = cameras || [];
  66881. // Initialize
  66882. _this._scene = scene;
  66883. _this._basePostProcess = originalPostProcess;
  66884. _this._ratio = ratio;
  66885. // Misc
  66886. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66887. // Finish
  66888. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66889. _this._buildPipeline();
  66890. return _this;
  66891. }
  66892. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66893. get: function () {
  66894. return this._bloomEnabled;
  66895. },
  66896. set: function (enabled) {
  66897. if (this._bloomEnabled === enabled) {
  66898. return;
  66899. }
  66900. this._bloomEnabled = enabled;
  66901. this._buildPipeline();
  66902. },
  66903. enumerable: true,
  66904. configurable: true
  66905. });
  66906. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66907. get: function () {
  66908. return this._depthOfFieldEnabled;
  66909. },
  66910. set: function (enabled) {
  66911. if (this._depthOfFieldEnabled === enabled) {
  66912. return;
  66913. }
  66914. this._depthOfFieldEnabled = enabled;
  66915. this._buildPipeline();
  66916. },
  66917. enumerable: true,
  66918. configurable: true
  66919. });
  66920. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66921. get: function () {
  66922. return this._lensFlareEnabled;
  66923. },
  66924. set: function (enabled) {
  66925. if (this._lensFlareEnabled === enabled) {
  66926. return;
  66927. }
  66928. this._lensFlareEnabled = enabled;
  66929. this._buildPipeline();
  66930. },
  66931. enumerable: true,
  66932. configurable: true
  66933. });
  66934. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66935. get: function () {
  66936. return this._hdrEnabled;
  66937. },
  66938. set: function (enabled) {
  66939. if (this._hdrEnabled === enabled) {
  66940. return;
  66941. }
  66942. this._hdrEnabled = enabled;
  66943. this._buildPipeline();
  66944. },
  66945. enumerable: true,
  66946. configurable: true
  66947. });
  66948. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66949. get: function () {
  66950. return this._vlsEnabled;
  66951. },
  66952. set: function (enabled) {
  66953. if (this._vlsEnabled === enabled) {
  66954. return;
  66955. }
  66956. if (enabled) {
  66957. var geometry = this._scene.enableGeometryBufferRenderer();
  66958. if (!geometry) {
  66959. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66960. return;
  66961. }
  66962. }
  66963. this._vlsEnabled = enabled;
  66964. this._buildPipeline();
  66965. },
  66966. enumerable: true,
  66967. configurable: true
  66968. });
  66969. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66970. get: function () {
  66971. return this._motionBlurEnabled;
  66972. },
  66973. set: function (enabled) {
  66974. if (this._motionBlurEnabled === enabled) {
  66975. return;
  66976. }
  66977. this._motionBlurEnabled = enabled;
  66978. this._buildPipeline();
  66979. },
  66980. enumerable: true,
  66981. configurable: true
  66982. });
  66983. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66984. get: function () {
  66985. return this._volumetricLightStepsCount;
  66986. },
  66987. set: function (count) {
  66988. if (this.volumetricLightPostProcess) {
  66989. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66990. }
  66991. this._volumetricLightStepsCount = count;
  66992. },
  66993. enumerable: true,
  66994. configurable: true
  66995. });
  66996. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66997. get: function () {
  66998. return this._motionBlurSamples;
  66999. },
  67000. set: function (samples) {
  67001. if (this.motionBlurPostProcess) {
  67002. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67003. }
  67004. this._motionBlurSamples = samples;
  67005. },
  67006. enumerable: true,
  67007. configurable: true
  67008. });
  67009. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67010. var _this = this;
  67011. var ratio = this._ratio;
  67012. var scene = this._scene;
  67013. this._disposePostProcesses();
  67014. this._reset();
  67015. // Create pass post-process
  67016. if (!this._basePostProcess) {
  67017. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67018. this.originalPostProcess.onApply = function (effect) {
  67019. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67020. };
  67021. }
  67022. else {
  67023. this.originalPostProcess = this._basePostProcess;
  67024. }
  67025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67026. this._currentDepthOfFieldSource = this.originalPostProcess;
  67027. if (this._vlsEnabled) {
  67028. // Create volumetric light
  67029. this._createVolumetricLightPostProcess(scene, ratio);
  67030. // Create volumetric light final post-process
  67031. 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);
  67032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67033. }
  67034. if (this._bloomEnabled) {
  67035. // Create down sample X4 post-process
  67036. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67037. // Create bright pass post-process
  67038. this._createBrightPassPostProcess(scene, ratio / 2);
  67039. // Create gaussian blur post-processes (down sampling blurs)
  67040. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67041. // Create texture adder post-process
  67042. this._createTextureAdderPostProcess(scene, ratio);
  67043. // Create depth-of-field source post-process
  67044. 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);
  67045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67046. }
  67047. if (this._lensFlareEnabled) {
  67048. // Create lens flare post-process
  67049. this._createLensFlarePostProcess(scene, ratio);
  67050. // Create depth-of-field source post-process post lens-flare and disable it now
  67051. 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);
  67052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67053. }
  67054. if (this._hdrEnabled) {
  67055. // Create luminance
  67056. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67057. // Create HDR
  67058. this._createHdrPostProcess(scene, ratio);
  67059. // Create depth-of-field source post-process post hdr and disable it now
  67060. 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);
  67061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67062. }
  67063. if (this._depthOfFieldEnabled) {
  67064. // Create gaussian blur used by depth-of-field
  67065. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67066. // Create depth-of-field post-process
  67067. this._createDepthOfFieldPostProcess(scene, ratio);
  67068. }
  67069. if (this._motionBlurEnabled) {
  67070. // Create motion blur post-process
  67071. this._createMotionBlurPostProcess(scene, ratio);
  67072. }
  67073. if (this._cameras !== null) {
  67074. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67075. }
  67076. };
  67077. // Down Sample X4 Post-Processs
  67078. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67079. var _this = this;
  67080. var downSampleX4Offsets = new Array(32);
  67081. 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);
  67082. this.downSampleX4PostProcess.onApply = function (effect) {
  67083. var id = 0;
  67084. var width = _this.downSampleX4PostProcess.width;
  67085. var height = _this.downSampleX4PostProcess.height;
  67086. for (var i = -2; i < 2; i++) {
  67087. for (var j = -2; j < 2; j++) {
  67088. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67089. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67090. id += 2;
  67091. }
  67092. }
  67093. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67094. };
  67095. // Add to pipeline
  67096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67097. };
  67098. // Brightpass Post-Process
  67099. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67100. var _this = this;
  67101. var brightOffsets = new Array(8);
  67102. 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);
  67103. this.brightPassPostProcess.onApply = function (effect) {
  67104. var sU = (1.0 / _this.brightPassPostProcess.width);
  67105. var sV = (1.0 / _this.brightPassPostProcess.height);
  67106. brightOffsets[0] = -0.5 * sU;
  67107. brightOffsets[1] = 0.5 * sV;
  67108. brightOffsets[2] = 0.5 * sU;
  67109. brightOffsets[3] = 0.5 * sV;
  67110. brightOffsets[4] = -0.5 * sU;
  67111. brightOffsets[5] = -0.5 * sV;
  67112. brightOffsets[6] = 0.5 * sU;
  67113. brightOffsets[7] = -0.5 * sV;
  67114. effect.setArray2("dsOffsets", brightOffsets);
  67115. effect.setFloat("brightThreshold", _this.brightThreshold);
  67116. };
  67117. // Add to pipeline
  67118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67119. };
  67120. // Create blur H&V post-processes
  67121. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67122. var _this = this;
  67123. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67124. var engine = scene.getEngine();
  67125. 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);
  67126. 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);
  67127. blurX.onActivateObservable.add(function () {
  67128. var dw = blurX.width / engine.getRenderWidth();
  67129. blurX.kernel = _this[blurWidthKey] * dw;
  67130. });
  67131. blurY.onActivateObservable.add(function () {
  67132. var dw = blurY.height / engine.getRenderHeight();
  67133. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67134. });
  67135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67137. this.blurHPostProcesses.push(blurX);
  67138. this.blurVPostProcesses.push(blurY);
  67139. };
  67140. // Create texture adder post-process
  67141. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67142. var _this = this;
  67143. 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);
  67144. this.textureAdderPostProcess.onApply = function (effect) {
  67145. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67146. effect.setTexture("lensSampler", _this.lensTexture);
  67147. effect.setFloat("exposure", _this.exposure);
  67148. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67149. };
  67150. // Add to pipeline
  67151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67152. };
  67153. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67154. var _this = this;
  67155. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67156. geometryRenderer.enablePosition = true;
  67157. var geometry = geometryRenderer.getGBuffer();
  67158. // Base post-process
  67159. 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));
  67160. var depthValues = BABYLON.Vector2.Zero();
  67161. this.volumetricLightPostProcess.onApply = function (effect) {
  67162. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67163. var generator = _this.sourceLight.getShadowGenerator();
  67164. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67165. effect.setTexture("positionSampler", geometry.textures[2]);
  67166. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67167. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67168. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67169. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67170. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67171. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67172. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67173. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67174. effect.setVector2("depthValues", depthValues);
  67175. }
  67176. };
  67177. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67178. // Smooth
  67179. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67180. // Merge
  67181. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67182. this.volumetricLightMergePostProces.onApply = function (effect) {
  67183. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67184. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67185. };
  67186. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67187. };
  67188. // Create luminance
  67189. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67190. var _this = this;
  67191. // Create luminance
  67192. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67193. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67194. var offsets = [];
  67195. this.luminancePostProcess.onApply = function (effect) {
  67196. var sU = (1.0 / _this.luminancePostProcess.width);
  67197. var sV = (1.0 / _this.luminancePostProcess.height);
  67198. offsets[0] = -0.5 * sU;
  67199. offsets[1] = 0.5 * sV;
  67200. offsets[2] = 0.5 * sU;
  67201. offsets[3] = 0.5 * sV;
  67202. offsets[4] = -0.5 * sU;
  67203. offsets[5] = -0.5 * sV;
  67204. offsets[6] = 0.5 * sU;
  67205. offsets[7] = -0.5 * sV;
  67206. effect.setArray2("lumOffsets", offsets);
  67207. };
  67208. // Add to pipeline
  67209. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67210. // Create down sample luminance
  67211. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67212. var size = Math.pow(3, i);
  67213. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67214. if (i === 0) {
  67215. defines += "#define FINAL_DOWN_SAMPLER";
  67216. }
  67217. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67218. this.luminanceDownSamplePostProcesses.push(postProcess);
  67219. }
  67220. // Create callbacks and add effects
  67221. var lastLuminance = this.luminancePostProcess;
  67222. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67223. var downSampleOffsets = new Array(18);
  67224. pp.onApply = function (effect) {
  67225. if (!lastLuminance) {
  67226. return;
  67227. }
  67228. var id = 0;
  67229. for (var x = -1; x < 2; x++) {
  67230. for (var y = -1; y < 2; y++) {
  67231. downSampleOffsets[id] = x / lastLuminance.width;
  67232. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67233. id += 2;
  67234. }
  67235. }
  67236. effect.setArray2("dsOffsets", downSampleOffsets);
  67237. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67238. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67239. lastLuminance = _this.luminancePostProcess;
  67240. }
  67241. else {
  67242. lastLuminance = pp;
  67243. }
  67244. };
  67245. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67246. pp.onAfterRender = function (effect) {
  67247. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67248. 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);
  67249. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67250. };
  67251. }
  67252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67253. });
  67254. };
  67255. // Create HDR post-process
  67256. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67257. var _this = this;
  67258. 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);
  67259. var outputLiminance = 1;
  67260. var time = 0;
  67261. var lastTime = 0;
  67262. this.hdrPostProcess.onApply = function (effect) {
  67263. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67264. time += scene.getEngine().getDeltaTime();
  67265. if (outputLiminance < 0) {
  67266. outputLiminance = _this._hdrCurrentLuminance;
  67267. }
  67268. else {
  67269. var dt = (lastTime - time) / 1000.0;
  67270. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67271. outputLiminance += _this.hdrDecreaseRate * dt;
  67272. }
  67273. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67274. outputLiminance -= _this.hdrIncreaseRate * dt;
  67275. }
  67276. else {
  67277. outputLiminance = _this._hdrCurrentLuminance;
  67278. }
  67279. }
  67280. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67281. effect.setFloat("averageLuminance", outputLiminance);
  67282. lastTime = time;
  67283. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67284. };
  67285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67286. };
  67287. // Create lens flare post-process
  67288. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67289. var _this = this;
  67290. 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);
  67291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67292. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67293. 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);
  67294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67295. var resolution = new BABYLON.Vector2(0, 0);
  67296. // Lens flare
  67297. this.lensFlarePostProcess.onApply = function (effect) {
  67298. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67299. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67300. effect.setFloat("strength", _this.lensFlareStrength);
  67301. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67302. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67303. // Shift
  67304. resolution.x = _this.lensFlarePostProcess.width;
  67305. resolution.y = _this.lensFlarePostProcess.height;
  67306. effect.setVector2("resolution", resolution);
  67307. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67308. };
  67309. // Compose
  67310. 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);
  67311. 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);
  67312. this.lensFlareComposePostProcess.onApply = function (effect) {
  67313. if (!_this._scene.activeCamera) {
  67314. return;
  67315. }
  67316. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67317. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67318. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67319. // Lens start rotation matrix
  67320. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67321. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67322. 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));
  67323. camRot *= 4.0;
  67324. 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);
  67325. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67326. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67327. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67328. };
  67329. };
  67330. // Create depth-of-field post-process
  67331. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67332. var _this = this;
  67333. 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);
  67334. this.depthOfFieldPostProcess.onApply = function (effect) {
  67335. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67336. effect.setTexture("depthSampler", _this._getDepthTexture());
  67337. effect.setFloat("distance", _this.depthOfFieldDistance);
  67338. };
  67339. // Add to pipeline
  67340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67341. };
  67342. // Create motion blur post-process
  67343. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67344. var _this = this;
  67345. 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);
  67346. var motionScale = 0;
  67347. var prevViewProjection = BABYLON.Matrix.Identity();
  67348. var invViewProjection = BABYLON.Matrix.Identity();
  67349. var viewProjection = BABYLON.Matrix.Identity();
  67350. var screenSize = BABYLON.Vector2.Zero();
  67351. this.motionBlurPostProcess.onApply = function (effect) {
  67352. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67353. viewProjection.invertToRef(invViewProjection);
  67354. effect.setMatrix("inverseViewProjection", invViewProjection);
  67355. effect.setMatrix("prevViewProjection", prevViewProjection);
  67356. prevViewProjection = viewProjection;
  67357. screenSize.x = _this.motionBlurPostProcess.width;
  67358. screenSize.y = _this.motionBlurPostProcess.height;
  67359. effect.setVector2("screenSize", screenSize);
  67360. motionScale = scene.getEngine().getFps() / 60.0;
  67361. effect.setFloat("motionScale", motionScale);
  67362. effect.setFloat("motionStrength", _this.motionStrength);
  67363. effect.setTexture("depthSampler", _this._getDepthTexture());
  67364. };
  67365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67366. };
  67367. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67368. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67369. var renderer = this._scene.enableGeometryBufferRenderer();
  67370. return renderer.getGBuffer().textures[0];
  67371. }
  67372. return this._scene.enableDepthRenderer().getDepthMap();
  67373. };
  67374. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67375. for (var i = 0; i < this._cameras.length; i++) {
  67376. var camera = this._cameras[i];
  67377. if (this.originalPostProcess) {
  67378. this.originalPostProcess.dispose(camera);
  67379. }
  67380. if (this.downSampleX4PostProcess) {
  67381. this.downSampleX4PostProcess.dispose(camera);
  67382. }
  67383. if (this.brightPassPostProcess) {
  67384. this.brightPassPostProcess.dispose(camera);
  67385. }
  67386. if (this.textureAdderPostProcess) {
  67387. this.textureAdderPostProcess.dispose(camera);
  67388. }
  67389. if (this.textureAdderFinalPostProcess) {
  67390. this.textureAdderFinalPostProcess.dispose(camera);
  67391. }
  67392. if (this.volumetricLightPostProcess) {
  67393. this.volumetricLightPostProcess.dispose(camera);
  67394. }
  67395. if (this.volumetricLightSmoothXPostProcess) {
  67396. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67397. }
  67398. if (this.volumetricLightSmoothYPostProcess) {
  67399. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67400. }
  67401. if (this.volumetricLightMergePostProces) {
  67402. this.volumetricLightMergePostProces.dispose(camera);
  67403. }
  67404. if (this.volumetricLightFinalPostProcess) {
  67405. this.volumetricLightFinalPostProcess.dispose(camera);
  67406. }
  67407. if (this.lensFlarePostProcess) {
  67408. this.lensFlarePostProcess.dispose(camera);
  67409. }
  67410. if (this.lensFlareComposePostProcess) {
  67411. this.lensFlareComposePostProcess.dispose(camera);
  67412. }
  67413. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67414. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67415. }
  67416. if (this.luminancePostProcess) {
  67417. this.luminancePostProcess.dispose(camera);
  67418. }
  67419. if (this.hdrPostProcess) {
  67420. this.hdrPostProcess.dispose(camera);
  67421. }
  67422. if (this.hdrFinalPostProcess) {
  67423. this.hdrFinalPostProcess.dispose(camera);
  67424. }
  67425. if (this.depthOfFieldPostProcess) {
  67426. this.depthOfFieldPostProcess.dispose(camera);
  67427. }
  67428. if (this.motionBlurPostProcess) {
  67429. this.motionBlurPostProcess.dispose(camera);
  67430. }
  67431. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67432. this.blurHPostProcesses[j].dispose(camera);
  67433. }
  67434. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67435. this.blurVPostProcesses[j].dispose(camera);
  67436. }
  67437. }
  67438. this.originalPostProcess = null;
  67439. this.downSampleX4PostProcess = null;
  67440. this.brightPassPostProcess = null;
  67441. this.textureAdderPostProcess = null;
  67442. this.textureAdderFinalPostProcess = null;
  67443. this.volumetricLightPostProcess = null;
  67444. this.volumetricLightSmoothXPostProcess = null;
  67445. this.volumetricLightSmoothYPostProcess = null;
  67446. this.volumetricLightMergePostProces = null;
  67447. this.volumetricLightFinalPostProcess = null;
  67448. this.lensFlarePostProcess = null;
  67449. this.lensFlareComposePostProcess = null;
  67450. this.luminancePostProcess = null;
  67451. this.hdrPostProcess = null;
  67452. this.hdrFinalPostProcess = null;
  67453. this.depthOfFieldPostProcess = null;
  67454. this.motionBlurPostProcess = null;
  67455. this.luminanceDownSamplePostProcesses = [];
  67456. this.blurHPostProcesses = [];
  67457. this.blurVPostProcesses = [];
  67458. };
  67459. // Dispose
  67460. StandardRenderingPipeline.prototype.dispose = function () {
  67461. this._disposePostProcesses();
  67462. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67463. _super.prototype.dispose.call(this);
  67464. };
  67465. // Serialize rendering pipeline
  67466. StandardRenderingPipeline.prototype.serialize = function () {
  67467. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67468. serializationObject.customType = "StandardRenderingPipeline";
  67469. return serializationObject;
  67470. };
  67471. /**
  67472. * Static members
  67473. */
  67474. // Parse serialized pipeline
  67475. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67476. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67477. };
  67478. // Luminance steps
  67479. StandardRenderingPipeline.LuminanceSteps = 6;
  67480. __decorate([
  67481. BABYLON.serialize()
  67482. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67483. __decorate([
  67484. BABYLON.serialize()
  67485. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67486. __decorate([
  67487. BABYLON.serialize()
  67488. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67489. __decorate([
  67490. BABYLON.serialize()
  67491. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67492. __decorate([
  67493. BABYLON.serializeAsTexture("lensTexture")
  67494. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67495. __decorate([
  67496. BABYLON.serialize()
  67497. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67498. __decorate([
  67499. BABYLON.serialize()
  67500. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67501. __decorate([
  67502. BABYLON.serialize()
  67503. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67504. __decorate([
  67505. BABYLON.serialize()
  67506. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67507. __decorate([
  67508. BABYLON.serialize()
  67509. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67510. __decorate([
  67511. BABYLON.serialize()
  67512. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67513. __decorate([
  67514. BABYLON.serializeAsTexture("lensColorTexture")
  67515. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67516. __decorate([
  67517. BABYLON.serialize()
  67518. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67519. __decorate([
  67520. BABYLON.serialize()
  67521. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67522. __decorate([
  67523. BABYLON.serialize()
  67524. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67525. __decorate([
  67526. BABYLON.serialize()
  67527. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67528. __decorate([
  67529. BABYLON.serializeAsTexture("lensStarTexture")
  67530. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67531. __decorate([
  67532. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67533. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67534. __decorate([
  67535. BABYLON.serialize()
  67536. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67537. __decorate([
  67538. BABYLON.serialize()
  67539. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67540. __decorate([
  67541. BABYLON.serialize()
  67542. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67543. __decorate([
  67544. BABYLON.serialize()
  67545. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67546. __decorate([
  67547. BABYLON.serialize()
  67548. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67549. __decorate([
  67550. BABYLON.serialize()
  67551. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67552. __decorate([
  67553. BABYLON.serialize()
  67554. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67555. __decorate([
  67556. BABYLON.serialize()
  67557. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67558. __decorate([
  67559. BABYLON.serialize()
  67560. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67561. __decorate([
  67562. BABYLON.serialize()
  67563. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67564. __decorate([
  67565. BABYLON.serialize()
  67566. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67567. __decorate([
  67568. BABYLON.serialize()
  67569. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67570. return StandardRenderingPipeline;
  67571. }(BABYLON.PostProcessRenderPipeline));
  67572. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67573. })(BABYLON || (BABYLON = {}));
  67574. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67575. var BABYLON;
  67576. (function (BABYLON) {
  67577. var FxaaPostProcess = /** @class */ (function (_super) {
  67578. __extends(FxaaPostProcess, _super);
  67579. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67580. if (camera === void 0) { camera = null; }
  67581. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67582. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67583. _this.onApplyObservable.add(function (effect) {
  67584. var texelSize = _this.texelSize;
  67585. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67586. });
  67587. return _this;
  67588. }
  67589. return FxaaPostProcess;
  67590. }(BABYLON.PostProcess));
  67591. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67592. })(BABYLON || (BABYLON = {}));
  67593. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67594. var BABYLON;
  67595. (function (BABYLON) {
  67596. /**
  67597. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67598. */
  67599. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67600. __extends(CircleOfConfusionPostProcess, _super);
  67601. /**
  67602. * Creates a new instance of @see CircleOfConfusionPostProcess
  67603. * @param name The name of the effect.
  67604. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67605. * @param options The required width/height ratio to downsize to before computing the render pass.
  67606. * @param camera The camera to apply the render pass to.
  67607. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67608. * @param engine The engine which the post process will be applied. (default: current engine)
  67609. * @param reusable If the post process can be reused on the same frame. (default: false)
  67610. * @param textureType Type of textures used when performing the post process. (default: 0)
  67611. */
  67612. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67613. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67614. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67615. /**
  67616. * 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.
  67617. */
  67618. _this.lensSize = 50;
  67619. /**
  67620. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67621. */
  67622. _this.fStop = 1.4;
  67623. /**
  67624. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67625. */
  67626. _this.focusDistance = 2000;
  67627. /**
  67628. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67629. */
  67630. _this.focalLength = 50;
  67631. _this.onApplyObservable.add(function (effect) {
  67632. effect.setTexture("depthSampler", depthTexture);
  67633. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67634. var aperture = _this.lensSize / _this.fStop;
  67635. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67636. effect.setFloat('focusDistance', _this.focusDistance);
  67637. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67638. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67639. });
  67640. return _this;
  67641. }
  67642. return CircleOfConfusionPostProcess;
  67643. }(BABYLON.PostProcess));
  67644. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67645. })(BABYLON || (BABYLON = {}));
  67646. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67647. var BABYLON;
  67648. (function (BABYLON) {
  67649. /**
  67650. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67651. */
  67652. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67653. __extends(DepthOfFieldMergePostProcess, _super);
  67654. /**
  67655. * Creates a new instance of @see CircleOfConfusionPostProcess
  67656. * @param name The name of the effect.
  67657. * @param original The non-blurred image to be modified
  67658. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67659. * @param blurSteps Incrimental bluring post processes.
  67660. * @param options The required width/height ratio to downsize to before computing the render pass.
  67661. * @param camera The camera to apply the render pass to.
  67662. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67663. * @param engine The engine which the post process will be applied. (default: current engine)
  67664. * @param reusable If the post process can be reused on the same frame. (default: false)
  67665. * @param textureType Type of textures used when performing the post process. (default: 0)
  67666. */
  67667. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67668. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67669. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67670. _this.onApplyObservable.add(function (effect) {
  67671. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67672. effect.setTextureFromPostProcess("originalSampler", original);
  67673. blurSteps.forEach(function (step, index) {
  67674. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67675. });
  67676. });
  67677. return _this;
  67678. }
  67679. return DepthOfFieldMergePostProcess;
  67680. }(BABYLON.PostProcess));
  67681. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67682. })(BABYLON || (BABYLON = {}));
  67683. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67684. var BABYLON;
  67685. (function (BABYLON) {
  67686. /**
  67687. * Specifies the level of max blur that should be applied when using the depth of field effect
  67688. */
  67689. var DepthOfFieldEffectBlurLevel;
  67690. (function (DepthOfFieldEffectBlurLevel) {
  67691. /**
  67692. * Subtle blur
  67693. */
  67694. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67695. /**
  67696. * Medium blur
  67697. */
  67698. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67699. /**
  67700. * Large blur
  67701. */
  67702. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67703. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67704. ;
  67705. /**
  67706. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67707. */
  67708. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67709. __extends(DepthOfFieldEffect, _super);
  67710. /**
  67711. * Creates a new instance of @see DepthOfFieldEffect
  67712. * @param scene The scene the effect belongs to.
  67713. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67714. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67715. */
  67716. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67717. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67718. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67719. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67720. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67721. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67722. // Capture circle of confusion texture
  67723. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67724. _this._depthOfFieldPass.autoClear = false;
  67725. // 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)
  67726. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67727. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67728. _this._depthOfFieldBlurY = [];
  67729. _this._depthOfFieldBlurX = [];
  67730. var blurCount = 1;
  67731. var kernelSize = 15;
  67732. switch (blurLevel) {
  67733. case DepthOfFieldEffectBlurLevel.High: {
  67734. blurCount = 3;
  67735. kernelSize = 51;
  67736. break;
  67737. }
  67738. case DepthOfFieldEffectBlurLevel.Medium: {
  67739. blurCount = 2;
  67740. kernelSize = 31;
  67741. break;
  67742. }
  67743. default: {
  67744. kernelSize = 15;
  67745. blurCount = 1;
  67746. break;
  67747. }
  67748. }
  67749. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67750. for (var i = 0; i < blurCount; i++) {
  67751. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67752. blurY.autoClear = false;
  67753. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67754. blurX.autoClear = false;
  67755. _this._depthOfFieldBlurY.push(blurY);
  67756. _this._depthOfFieldBlurX.push(blurX);
  67757. }
  67758. // Merge blurred images with original image based on circleOfConfusion
  67759. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67760. _this._depthOfFieldMerge.autoClear = false;
  67761. // Set all post processes on the effect.
  67762. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67763. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67764. effects.push(_this._depthOfFieldBlurY[i]);
  67765. effects.push(_this._depthOfFieldBlurX[i]);
  67766. }
  67767. effects.push(_this._depthOfFieldMerge);
  67768. return effects;
  67769. }, true) || this;
  67770. return _this;
  67771. }
  67772. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67773. get: function () {
  67774. return this._circleOfConfusion.focalLength;
  67775. },
  67776. /**
  67777. * The focal the length of the camera used in the effect
  67778. */
  67779. set: function (value) {
  67780. this._circleOfConfusion.focalLength = value;
  67781. },
  67782. enumerable: true,
  67783. configurable: true
  67784. });
  67785. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67786. get: function () {
  67787. return this._circleOfConfusion.fStop;
  67788. },
  67789. /**
  67790. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67791. */
  67792. set: function (value) {
  67793. this._circleOfConfusion.fStop = value;
  67794. },
  67795. enumerable: true,
  67796. configurable: true
  67797. });
  67798. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67799. get: function () {
  67800. return this._circleOfConfusion.focusDistance;
  67801. },
  67802. /**
  67803. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67804. */
  67805. set: function (value) {
  67806. this._circleOfConfusion.focusDistance = value;
  67807. },
  67808. enumerable: true,
  67809. configurable: true
  67810. });
  67811. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67812. get: function () {
  67813. return this._circleOfConfusion.lensSize;
  67814. },
  67815. /**
  67816. * 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.
  67817. */
  67818. set: function (value) {
  67819. this._circleOfConfusion.lensSize = value;
  67820. },
  67821. enumerable: true,
  67822. configurable: true
  67823. });
  67824. /**
  67825. * Disposes each of the internal effects for a given camera.
  67826. * @param camera The camera to dispose the effect on.
  67827. */
  67828. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67829. this._depthOfFieldPass.dispose(camera);
  67830. this._circleOfConfusion.dispose(camera);
  67831. this._depthOfFieldBlurX.forEach(function (element) {
  67832. element.dispose(camera);
  67833. });
  67834. this._depthOfFieldBlurY.forEach(function (element) {
  67835. element.dispose(camera);
  67836. });
  67837. this._depthOfFieldMerge.dispose(camera);
  67838. };
  67839. return DepthOfFieldEffect;
  67840. }(BABYLON.PostProcessRenderEffect));
  67841. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67842. })(BABYLON || (BABYLON = {}));
  67843. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67844. var BABYLON;
  67845. (function (BABYLON) {
  67846. /**
  67847. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67848. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67849. */
  67850. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67851. __extends(DefaultRenderingPipeline, _super);
  67852. /**
  67853. * @constructor
  67854. * @param {string} name - The rendering pipeline name
  67855. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67856. * @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)
  67857. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67858. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67859. */
  67860. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67861. if (automaticBuild === void 0) { automaticBuild = true; }
  67862. var _this = _super.call(this, scene.getEngine(), name) || this;
  67863. /**
  67864. * ID of the sharpen post process,
  67865. */
  67866. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67867. /**
  67868. * ID of the pass post process used for bloom,
  67869. */
  67870. _this.PassPostProcessId = "PassPostProcessEffect";
  67871. /**
  67872. * ID of the highlight post process used for bloom,
  67873. */
  67874. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67875. /**
  67876. * ID of the blurX post process used for bloom,
  67877. */
  67878. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67879. /**
  67880. * ID of the blurY post process used for bloom,
  67881. */
  67882. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67883. /**
  67884. * ID of the copy back post process used for bloom,
  67885. */
  67886. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67887. /**
  67888. * ID of the image processing post process;
  67889. */
  67890. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67891. /**
  67892. * ID of the Fast Approximate Anti-Aliasing post process;
  67893. */
  67894. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67895. /**
  67896. * ID of the final merge post process;
  67897. */
  67898. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67899. /**
  67900. * ID of the chromatic aberration post process,
  67901. */
  67902. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  67903. /**
  67904. * Animations which can be used to tweak settings over a period of time
  67905. */
  67906. _this.animations = [];
  67907. // Values
  67908. _this._sharpenEnabled = false;
  67909. _this._bloomEnabled = false;
  67910. _this._depthOfFieldEnabled = false;
  67911. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67912. _this._fxaaEnabled = false;
  67913. _this._msaaEnabled = false;
  67914. _this._imageProcessingEnabled = true;
  67915. _this._bloomScale = 0.6;
  67916. _this._chromaticAberrationEnabled = false;
  67917. _this._buildAllowed = true;
  67918. /**
  67919. * Specifies the size of the bloom blur kernel, relative to the final output size
  67920. */
  67921. _this.bloomKernel = 64;
  67922. /**
  67923. * Specifies the weight of the bloom in the final rendering
  67924. */
  67925. _this._bloomWeight = 0.15;
  67926. _this._cameras = cameras || [];
  67927. _this._buildAllowed = automaticBuild;
  67928. // Initialize
  67929. _this._scene = scene;
  67930. var caps = _this._scene.getEngine().getCaps();
  67931. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67932. // Misc
  67933. if (_this._hdr) {
  67934. if (caps.textureHalfFloatRender) {
  67935. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67936. }
  67937. else if (caps.textureFloatRender) {
  67938. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67939. }
  67940. }
  67941. else {
  67942. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67943. }
  67944. // Attach
  67945. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67946. _this._buildPipeline();
  67947. return _this;
  67948. }
  67949. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  67950. get: function () {
  67951. return this._sharpenEnabled;
  67952. },
  67953. /**
  67954. * Enable or disable the sharpen process from the pipeline
  67955. */
  67956. set: function (enabled) {
  67957. if (this._sharpenEnabled === enabled) {
  67958. return;
  67959. }
  67960. this._sharpenEnabled = enabled;
  67961. this._buildPipeline();
  67962. },
  67963. enumerable: true,
  67964. configurable: true
  67965. });
  67966. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67967. get: function () {
  67968. return this._bloomWeight;
  67969. },
  67970. /**
  67971. * The strength of the bloom.
  67972. */
  67973. set: function (value) {
  67974. if (this._bloomWeight === value) {
  67975. return;
  67976. }
  67977. this._bloomWeight = value;
  67978. if (this._hdr && this.copyBack) {
  67979. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67980. }
  67981. },
  67982. enumerable: true,
  67983. configurable: true
  67984. });
  67985. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67986. get: function () {
  67987. return this._bloomScale;
  67988. },
  67989. /**
  67990. * The scale of the bloom, lower value will provide better performance.
  67991. */
  67992. set: function (value) {
  67993. if (this._bloomScale === value) {
  67994. return;
  67995. }
  67996. this._bloomScale = value;
  67997. this._buildPipeline();
  67998. },
  67999. enumerable: true,
  68000. configurable: true
  68001. });
  68002. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68003. get: function () {
  68004. return this._bloomEnabled;
  68005. },
  68006. /**
  68007. * Enable or disable the bloom from the pipeline
  68008. */
  68009. set: function (enabled) {
  68010. if (this._bloomEnabled === enabled) {
  68011. return;
  68012. }
  68013. this._bloomEnabled = enabled;
  68014. this._buildPipeline();
  68015. },
  68016. enumerable: true,
  68017. configurable: true
  68018. });
  68019. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68020. /**
  68021. * If the depth of field is enabled.
  68022. */
  68023. get: function () {
  68024. return this._depthOfFieldEnabled;
  68025. },
  68026. set: function (enabled) {
  68027. if (this._depthOfFieldEnabled === enabled) {
  68028. return;
  68029. }
  68030. this._depthOfFieldEnabled = enabled;
  68031. this._buildPipeline();
  68032. },
  68033. enumerable: true,
  68034. configurable: true
  68035. });
  68036. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68037. /**
  68038. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68039. */
  68040. get: function () {
  68041. return this._depthOfFieldBlurLevel;
  68042. },
  68043. set: function (value) {
  68044. if (this._depthOfFieldBlurLevel === value) {
  68045. return;
  68046. }
  68047. this._depthOfFieldBlurLevel = value;
  68048. this._buildPipeline();
  68049. },
  68050. enumerable: true,
  68051. configurable: true
  68052. });
  68053. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68054. get: function () {
  68055. return this._fxaaEnabled;
  68056. },
  68057. /**
  68058. * If the anti aliasing is enabled.
  68059. */
  68060. set: function (enabled) {
  68061. if (this._fxaaEnabled === enabled) {
  68062. return;
  68063. }
  68064. this._fxaaEnabled = enabled;
  68065. this._buildPipeline();
  68066. },
  68067. enumerable: true,
  68068. configurable: true
  68069. });
  68070. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68071. get: function () {
  68072. return this._msaaEnabled;
  68073. },
  68074. /**
  68075. * If the multisample anti-aliasing is enabled.
  68076. */
  68077. set: function (enabled) {
  68078. if (this._msaaEnabled === enabled) {
  68079. return;
  68080. }
  68081. this._msaaEnabled = enabled;
  68082. this._buildPipeline();
  68083. },
  68084. enumerable: true,
  68085. configurable: true
  68086. });
  68087. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68088. get: function () {
  68089. return this._imageProcessingEnabled;
  68090. },
  68091. /**
  68092. * If image processing is enabled.
  68093. */
  68094. set: function (enabled) {
  68095. if (this._imageProcessingEnabled === enabled) {
  68096. return;
  68097. }
  68098. this._imageProcessingEnabled = enabled;
  68099. this._buildPipeline();
  68100. },
  68101. enumerable: true,
  68102. configurable: true
  68103. });
  68104. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68105. get: function () {
  68106. return this._chromaticAberrationEnabled;
  68107. },
  68108. /**
  68109. * Enable or disable the chromaticAberration process from the pipeline
  68110. */
  68111. set: function (enabled) {
  68112. if (this._chromaticAberrationEnabled === enabled) {
  68113. return;
  68114. }
  68115. this._chromaticAberrationEnabled = enabled;
  68116. this._buildPipeline();
  68117. },
  68118. enumerable: true,
  68119. configurable: true
  68120. });
  68121. /**
  68122. * Force the compilation of the entire pipeline.
  68123. */
  68124. DefaultRenderingPipeline.prototype.prepare = function () {
  68125. var previousState = this._buildAllowed;
  68126. this._buildAllowed = true;
  68127. this._buildPipeline();
  68128. this._buildAllowed = previousState;
  68129. };
  68130. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68131. var _this = this;
  68132. if (!this._buildAllowed) {
  68133. return;
  68134. }
  68135. var engine = this._scene.getEngine();
  68136. this._disposePostProcesses();
  68137. this._reset();
  68138. if (this.sharpenEnabled) {
  68139. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68140. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  68141. }
  68142. if (this.depthOfFieldEnabled) {
  68143. // Enable and get current depth map
  68144. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68145. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68146. this.addEffect(this.depthOfField);
  68147. }
  68148. if (this.bloomEnabled) {
  68149. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68150. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68151. if (!this._hdr) {
  68152. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68153. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68154. this.highlights.autoClear = false;
  68155. this.highlights.alwaysForcePOT = true;
  68156. }
  68157. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68158. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68159. this.blurX.alwaysForcePOT = true;
  68160. this.blurX.autoClear = false;
  68161. this.blurX.onActivateObservable.add(function () {
  68162. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68163. _this.blurX.kernel = _this.bloomKernel * dw;
  68164. });
  68165. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68166. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68167. this.blurY.alwaysForcePOT = true;
  68168. this.blurY.autoClear = false;
  68169. this.blurY.onActivateObservable.add(function () {
  68170. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68171. _this.blurY.kernel = _this.bloomKernel * dh;
  68172. });
  68173. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68174. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68175. this.copyBack.alwaysForcePOT = true;
  68176. if (this._hdr) {
  68177. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68178. var w = this.bloomWeight;
  68179. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68180. }
  68181. else {
  68182. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68183. }
  68184. this.copyBack.autoClear = false;
  68185. }
  68186. if (this._imageProcessingEnabled) {
  68187. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68188. if (this._hdr) {
  68189. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68190. }
  68191. else {
  68192. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68193. }
  68194. }
  68195. if (this.fxaaEnabled) {
  68196. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68197. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68198. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68199. }
  68200. else if (this._hdr && this.imageProcessing) {
  68201. this.finalMerge = this.imageProcessing;
  68202. }
  68203. else {
  68204. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68205. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68206. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68207. }
  68208. if (this.bloomEnabled) {
  68209. if (this._hdr) {
  68210. this.copyBack.shareOutputWith(this.blurX);
  68211. if (this.imageProcessing) {
  68212. this.imageProcessing.shareOutputWith(this.pass);
  68213. this.imageProcessing.autoClear = false;
  68214. }
  68215. else if (this.fxaa) {
  68216. this.fxaa.shareOutputWith(this.pass);
  68217. }
  68218. else {
  68219. this.finalMerge.shareOutputWith(this.pass);
  68220. }
  68221. }
  68222. else {
  68223. if (this.fxaa) {
  68224. this.fxaa.shareOutputWith(this.pass);
  68225. }
  68226. else {
  68227. this.finalMerge.shareOutputWith(this.pass);
  68228. }
  68229. }
  68230. }
  68231. if (this.chromaticAberrationEnabled) {
  68232. this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68233. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true));
  68234. }
  68235. if (this._cameras !== null) {
  68236. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68237. }
  68238. if (this.msaaEnabled) {
  68239. if (!this._enableMSAAOnFirstPostProcess()) {
  68240. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68241. }
  68242. }
  68243. };
  68244. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68245. for (var i = 0; i < this._cameras.length; i++) {
  68246. var camera = this._cameras[i];
  68247. if (this.sharpen) {
  68248. this.sharpen.dispose(camera);
  68249. }
  68250. if (this.pass) {
  68251. this.pass.dispose(camera);
  68252. }
  68253. if (this.highlights) {
  68254. this.highlights.dispose(camera);
  68255. }
  68256. if (this.blurX) {
  68257. this.blurX.dispose(camera);
  68258. }
  68259. if (this.blurY) {
  68260. this.blurY.dispose(camera);
  68261. }
  68262. if (this.copyBack) {
  68263. this.copyBack.dispose(camera);
  68264. }
  68265. if (this.imageProcessing) {
  68266. this.imageProcessing.dispose(camera);
  68267. }
  68268. if (this.fxaa) {
  68269. this.fxaa.dispose(camera);
  68270. }
  68271. if (this.finalMerge) {
  68272. this.finalMerge.dispose(camera);
  68273. }
  68274. if (this.depthOfField) {
  68275. this.depthOfField.disposeEffects(camera);
  68276. }
  68277. if (this.chromaticAberration) {
  68278. this.chromaticAberration.dispose(camera);
  68279. }
  68280. }
  68281. this.sharpen = null;
  68282. this.pass = null;
  68283. this.highlights = null;
  68284. this.blurX = null;
  68285. this.blurY = null;
  68286. this.copyBack = null;
  68287. this.imageProcessing = null;
  68288. this.fxaa = null;
  68289. this.finalMerge = null;
  68290. this.depthOfField = null;
  68291. this.chromaticAberration = null;
  68292. };
  68293. /**
  68294. * Dispose of the pipeline and stop all post processes
  68295. */
  68296. DefaultRenderingPipeline.prototype.dispose = function () {
  68297. this._disposePostProcesses();
  68298. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68299. _super.prototype.dispose.call(this);
  68300. };
  68301. /**
  68302. * Serialize the rendering pipeline (Used when exporting)
  68303. * @returns the serialized object
  68304. */
  68305. DefaultRenderingPipeline.prototype.serialize = function () {
  68306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68307. serializationObject.customType = "DefaultRenderingPipeline";
  68308. return serializationObject;
  68309. };
  68310. /**
  68311. * Parse the serialized pipeline
  68312. * @param source Source pipeline.
  68313. * @param scene The scene to load the pipeline to.
  68314. * @param rootUrl The URL of the serialized pipeline.
  68315. * @returns An instantiated pipeline from the serialized object.
  68316. */
  68317. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68318. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68319. };
  68320. __decorate([
  68321. BABYLON.serialize()
  68322. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68323. __decorate([
  68324. BABYLON.serialize()
  68325. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68326. __decorate([
  68327. BABYLON.serialize()
  68328. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68329. __decorate([
  68330. BABYLON.serialize()
  68331. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68332. __decorate([
  68333. BABYLON.serialize()
  68334. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68335. __decorate([
  68336. BABYLON.serialize()
  68337. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68338. __decorate([
  68339. BABYLON.serialize()
  68340. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68341. __decorate([
  68342. BABYLON.serialize()
  68343. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68344. __decorate([
  68345. BABYLON.serialize()
  68346. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68347. __decorate([
  68348. BABYLON.serialize()
  68349. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68350. __decorate([
  68351. BABYLON.serialize()
  68352. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68353. __decorate([
  68354. BABYLON.serialize()
  68355. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68356. __decorate([
  68357. BABYLON.serialize()
  68358. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  68359. return DefaultRenderingPipeline;
  68360. }(BABYLON.PostProcessRenderPipeline));
  68361. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68362. })(BABYLON || (BABYLON = {}));
  68363. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68364. var BABYLON;
  68365. (function (BABYLON) {
  68366. /**
  68367. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68368. */
  68369. var GeometryBufferRenderer = /** @class */ (function () {
  68370. /**
  68371. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68372. * @param scene The scene the buffer belongs to
  68373. * @param ratio How big is the buffer related to the main canvas.
  68374. */
  68375. function GeometryBufferRenderer(scene, ratio) {
  68376. if (ratio === void 0) { ratio = 1; }
  68377. this._enablePosition = false;
  68378. this._scene = scene;
  68379. this._ratio = ratio;
  68380. // Render target
  68381. this._createRenderTargets();
  68382. }
  68383. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68384. /**
  68385. * Set the render list (meshes to be rendered) used in the G buffer.
  68386. */
  68387. set: function (meshes) {
  68388. this._multiRenderTarget.renderList = meshes;
  68389. },
  68390. enumerable: true,
  68391. configurable: true
  68392. });
  68393. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68394. /**
  68395. * Gets wether or not G buffer are supported by the running hardware.
  68396. * This requires draw buffer supports
  68397. */
  68398. get: function () {
  68399. return this._multiRenderTarget.isSupported;
  68400. },
  68401. enumerable: true,
  68402. configurable: true
  68403. });
  68404. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68405. /**
  68406. * Gets wether or not position are enabled for the G buffer.
  68407. */
  68408. get: function () {
  68409. return this._enablePosition;
  68410. },
  68411. /**
  68412. * Sets wether or not position are enabled for the G buffer.
  68413. */
  68414. set: function (enable) {
  68415. this._enablePosition = enable;
  68416. this.dispose();
  68417. this._createRenderTargets();
  68418. },
  68419. enumerable: true,
  68420. configurable: true
  68421. });
  68422. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68423. /**
  68424. * Gets the scene associated with the buffer.
  68425. */
  68426. get: function () {
  68427. return this._scene;
  68428. },
  68429. enumerable: true,
  68430. configurable: true
  68431. });
  68432. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68433. /**
  68434. * Gets the ratio used by the buffer during its creation.
  68435. * How big is the buffer related to the main canvas.
  68436. */
  68437. get: function () {
  68438. return this._ratio;
  68439. },
  68440. enumerable: true,
  68441. configurable: true
  68442. });
  68443. /**
  68444. * Checks wether everything is ready to render a submesh to the G buffer.
  68445. * @param subMesh the submesh to check readiness for
  68446. * @param useInstances is the mesh drawn using instance or not
  68447. * @returns true if ready otherwise false
  68448. */
  68449. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68450. var material = subMesh.getMaterial();
  68451. if (material && material.disableDepthWrite) {
  68452. return false;
  68453. }
  68454. var defines = [];
  68455. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68456. var mesh = subMesh.getMesh();
  68457. // Alpha test
  68458. if (material && material.needAlphaTesting()) {
  68459. defines.push("#define ALPHATEST");
  68460. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68461. attribs.push(BABYLON.VertexBuffer.UVKind);
  68462. defines.push("#define UV1");
  68463. }
  68464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68466. defines.push("#define UV2");
  68467. }
  68468. }
  68469. // Buffers
  68470. if (this._enablePosition) {
  68471. defines.push("#define POSITION");
  68472. }
  68473. // Bones
  68474. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68477. if (mesh.numBoneInfluencers > 4) {
  68478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68480. }
  68481. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68482. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68483. }
  68484. else {
  68485. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68486. }
  68487. // Instances
  68488. if (useInstances) {
  68489. defines.push("#define INSTANCES");
  68490. attribs.push("world0");
  68491. attribs.push("world1");
  68492. attribs.push("world2");
  68493. attribs.push("world3");
  68494. }
  68495. // Get correct effect
  68496. var join = defines.join("\n");
  68497. if (this._cachedDefines !== join) {
  68498. this._cachedDefines = join;
  68499. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68500. }
  68501. return this._effect.isReady();
  68502. };
  68503. /**
  68504. * Gets the current underlying G Buffer.
  68505. * @returns the buffer
  68506. */
  68507. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68508. return this._multiRenderTarget;
  68509. };
  68510. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68511. /**
  68512. * Gets the number of samples used to render the buffer (anti aliasing).
  68513. */
  68514. get: function () {
  68515. return this._multiRenderTarget.samples;
  68516. },
  68517. /**
  68518. * Sets the number of samples used to render the buffer (anti aliasing).
  68519. */
  68520. set: function (value) {
  68521. this._multiRenderTarget.samples = value;
  68522. },
  68523. enumerable: true,
  68524. configurable: true
  68525. });
  68526. /**
  68527. * Disposes the renderer and frees up associated resources.
  68528. */
  68529. GeometryBufferRenderer.prototype.dispose = function () {
  68530. this.getGBuffer().dispose();
  68531. };
  68532. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68533. var _this = this;
  68534. var engine = this._scene.getEngine();
  68535. var count = this._enablePosition ? 3 : 2;
  68536. 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 });
  68537. if (!this.isSupported) {
  68538. return;
  68539. }
  68540. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68541. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68542. this._multiRenderTarget.refreshRate = 1;
  68543. this._multiRenderTarget.renderParticles = false;
  68544. this._multiRenderTarget.renderList = null;
  68545. // set default depth value to 1.0 (far away)
  68546. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68547. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68548. });
  68549. // Custom render function
  68550. var renderSubMesh = function (subMesh) {
  68551. var mesh = subMesh.getRenderingMesh();
  68552. var scene = _this._scene;
  68553. var engine = scene.getEngine();
  68554. var material = subMesh.getMaterial();
  68555. if (!material) {
  68556. return;
  68557. }
  68558. // Culling
  68559. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68560. // Managing instances
  68561. var batch = mesh._getInstancesRenderList(subMesh._id);
  68562. if (batch.mustReturn) {
  68563. return;
  68564. }
  68565. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68566. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68567. engine.enableEffect(_this._effect);
  68568. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68569. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68570. _this._effect.setMatrix("view", scene.getViewMatrix());
  68571. // Alpha test
  68572. if (material && material.needAlphaTesting()) {
  68573. var alphaTexture = material.getAlphaTestTexture();
  68574. if (alphaTexture) {
  68575. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68576. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68577. }
  68578. }
  68579. // Bones
  68580. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68581. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68582. }
  68583. // Draw
  68584. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68585. }
  68586. };
  68587. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68588. var index;
  68589. if (depthOnlySubMeshes.length) {
  68590. engine.setColorWrite(false);
  68591. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68592. renderSubMesh(depthOnlySubMeshes.data[index]);
  68593. }
  68594. engine.setColorWrite(true);
  68595. }
  68596. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68597. renderSubMesh(opaqueSubMeshes.data[index]);
  68598. }
  68599. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68600. renderSubMesh(alphaTestSubMeshes.data[index]);
  68601. }
  68602. };
  68603. };
  68604. return GeometryBufferRenderer;
  68605. }());
  68606. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68607. })(BABYLON || (BABYLON = {}));
  68608. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68609. var BABYLON;
  68610. (function (BABYLON) {
  68611. var RefractionPostProcess = /** @class */ (function (_super) {
  68612. __extends(RefractionPostProcess, _super);
  68613. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68614. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68615. _this.color = color;
  68616. _this.depth = depth;
  68617. _this.colorLevel = colorLevel;
  68618. _this._ownRefractionTexture = true;
  68619. _this.onActivateObservable.add(function (cam) {
  68620. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68621. });
  68622. _this.onApplyObservable.add(function (effect) {
  68623. effect.setColor3("baseColor", _this.color);
  68624. effect.setFloat("depth", _this.depth);
  68625. effect.setFloat("colorLevel", _this.colorLevel);
  68626. effect.setTexture("refractionSampler", _this._refTexture);
  68627. });
  68628. return _this;
  68629. }
  68630. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68631. /**
  68632. * Gets or sets the refraction texture
  68633. * Please note that you are responsible for disposing the texture if you set it manually
  68634. */
  68635. get: function () {
  68636. return this._refTexture;
  68637. },
  68638. set: function (value) {
  68639. if (this._refTexture && this._ownRefractionTexture) {
  68640. this._refTexture.dispose();
  68641. }
  68642. this._refTexture = value;
  68643. this._ownRefractionTexture = false;
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. // Methods
  68649. RefractionPostProcess.prototype.dispose = function (camera) {
  68650. if (this._refTexture && this._ownRefractionTexture) {
  68651. this._refTexture.dispose();
  68652. this._refTexture = null;
  68653. }
  68654. _super.prototype.dispose.call(this, camera);
  68655. };
  68656. return RefractionPostProcess;
  68657. }(BABYLON.PostProcess));
  68658. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68659. })(BABYLON || (BABYLON = {}));
  68660. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68661. var BABYLON;
  68662. (function (BABYLON) {
  68663. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68664. __extends(BlackAndWhitePostProcess, _super);
  68665. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68666. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68667. _this.degree = 1;
  68668. _this.onApplyObservable.add(function (effect) {
  68669. effect.setFloat("degree", _this.degree);
  68670. });
  68671. return _this;
  68672. }
  68673. return BlackAndWhitePostProcess;
  68674. }(BABYLON.PostProcess));
  68675. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68676. })(BABYLON || (BABYLON = {}));
  68677. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68678. var BABYLON;
  68679. (function (BABYLON) {
  68680. /**
  68681. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68682. * input texture to perform effects such as edge detection or sharpening
  68683. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68684. */
  68685. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68686. __extends(ConvolutionPostProcess, _super);
  68687. /**
  68688. * Creates a new instance of @see ConvolutionPostProcess
  68689. * @param name The name of the effect.
  68690. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68691. * @param options The required width/height ratio to downsize to before computing the render pass.
  68692. * @param camera The camera to apply the render pass to.
  68693. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68694. * @param engine The engine which the post process will be applied. (default: current engine)
  68695. * @param reusable If the post process can be reused on the same frame. (default: false)
  68696. * @param textureType Type of textures used when performing the post process. (default: 0)
  68697. */
  68698. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68699. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68700. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68701. _this.kernel = kernel;
  68702. _this.onApply = function (effect) {
  68703. effect.setFloat2("screenSize", _this.width, _this.height);
  68704. effect.setArray("kernel", _this.kernel);
  68705. };
  68706. return _this;
  68707. }
  68708. // Statics
  68709. /**
  68710. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68711. */
  68712. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68713. /**
  68714. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68715. */
  68716. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68717. /**
  68718. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68719. */
  68720. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68721. /**
  68722. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68723. */
  68724. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68725. /**
  68726. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68727. */
  68728. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68729. /**
  68730. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68731. */
  68732. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68733. return ConvolutionPostProcess;
  68734. }(BABYLON.PostProcess));
  68735. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68736. })(BABYLON || (BABYLON = {}));
  68737. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68738. var BABYLON;
  68739. (function (BABYLON) {
  68740. /**
  68741. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68742. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68743. */
  68744. var SharpenPostProcess = /** @class */ (function (_super) {
  68745. __extends(SharpenPostProcess, _super);
  68746. /**
  68747. * Creates a new instance of @see ConvolutionPostProcess
  68748. * @param name The name of the effect.
  68749. * @param options The required width/height ratio to downsize to before computing the render pass.
  68750. * @param camera The camera to apply the render pass to.
  68751. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68752. * @param engine The engine which the post process will be applied. (default: current engine)
  68753. * @param reusable If the post process can be reused on the same frame. (default: false)
  68754. * @param textureType Type of textures used when performing the post process. (default: 0)
  68755. */
  68756. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68757. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68758. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68759. /**
  68760. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68761. */
  68762. _this.colorAmount = 1.0;
  68763. /**
  68764. * How much sharpness should be applied (default: 0.3)
  68765. */
  68766. _this.edgeAmount = 0.3;
  68767. _this.onApply = function (effect) {
  68768. effect.setFloat2("screenSize", _this.width, _this.height);
  68769. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68770. };
  68771. return _this;
  68772. }
  68773. return SharpenPostProcess;
  68774. }(BABYLON.PostProcess));
  68775. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68776. })(BABYLON || (BABYLON = {}));
  68777. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68778. var BABYLON;
  68779. (function (BABYLON) {
  68780. /**
  68781. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68782. */
  68783. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68784. __extends(ChromaticAberrationPostProcess, _super);
  68785. /**
  68786. * Creates a new instance of @see ChromaticAberrationPostProcess
  68787. * @param name The name of the effect.
  68788. * @param screenWidth The width of the screen to apply the effect on.
  68789. * @param screenHeight The height of the screen to apply the effect on.
  68790. * @param options The required width/height ratio to downsize to before computing the render pass.
  68791. * @param camera The camera to apply the render pass to.
  68792. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68793. * @param engine The engine which the post process will be applied. (default: current engine)
  68794. * @param reusable If the post process can be reused on the same frame. (default: false)
  68795. * @param textureType Type of textures used when performing the post process. (default: 0)
  68796. */
  68797. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  68798. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68799. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68800. /**
  68801. * The amount of seperation of rgb channels (default: 0)
  68802. */
  68803. _this.aberrationAmount = 0;
  68804. /**
  68805. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68806. */
  68807. _this.radialIntensity = 0;
  68808. /**
  68809. * 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))
  68810. */
  68811. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68812. /**
  68813. * 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))
  68814. */
  68815. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68816. _this.onApplyObservable.add(function (effect) {
  68817. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68818. effect.setFloat('screen_width', screenWidth);
  68819. effect.setFloat('screen_height', screenHeight);
  68820. effect.setFloat('radialIntensity', _this.radialIntensity);
  68821. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68822. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68823. });
  68824. return _this;
  68825. }
  68826. return ChromaticAberrationPostProcess;
  68827. }(BABYLON.PostProcess));
  68828. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68829. })(BABYLON || (BABYLON = {}));
  68830. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68831. var BABYLON;
  68832. (function (BABYLON) {
  68833. var FilterPostProcess = /** @class */ (function (_super) {
  68834. __extends(FilterPostProcess, _super);
  68835. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68836. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68837. _this.kernelMatrix = kernelMatrix;
  68838. _this.onApply = function (effect) {
  68839. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68840. };
  68841. return _this;
  68842. }
  68843. return FilterPostProcess;
  68844. }(BABYLON.PostProcess));
  68845. BABYLON.FilterPostProcess = FilterPostProcess;
  68846. })(BABYLON || (BABYLON = {}));
  68847. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68848. var BABYLON;
  68849. (function (BABYLON) {
  68850. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68851. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68852. __extends(VolumetricLightScatteringPostProcess, _super);
  68853. /**
  68854. * @constructor
  68855. * @param {string} name - The post-process name
  68856. * @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)
  68857. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68858. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68859. * @param {number} samples - The post-process quality, default 100
  68860. * @param {number} samplingMode - The post-process filtering mode
  68861. * @param {BABYLON.Engine} engine - The babylon engine
  68862. * @param {boolean} reusable - If the post-process is reusable
  68863. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68864. */
  68865. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68866. if (samples === void 0) { samples = 100; }
  68867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68868. 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;
  68869. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68870. /**
  68871. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68872. * @type {Vector3}
  68873. */
  68874. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68875. /**
  68876. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68877. * @type {boolean}
  68878. */
  68879. _this.useCustomMeshPosition = false;
  68880. /**
  68881. * If the post-process should inverse the light scattering direction
  68882. * @type {boolean}
  68883. */
  68884. _this.invert = true;
  68885. /**
  68886. * Array containing the excluded meshes not rendered in the internal pass
  68887. */
  68888. _this.excludedMeshes = new Array();
  68889. /**
  68890. * Controls the overall intensity of the post-process
  68891. * @type {number}
  68892. */
  68893. _this.exposure = 0.3;
  68894. /**
  68895. * Dissipates each sample's contribution in range [0, 1]
  68896. * @type {number}
  68897. */
  68898. _this.decay = 0.96815;
  68899. /**
  68900. * Controls the overall intensity of each sample
  68901. * @type {number}
  68902. */
  68903. _this.weight = 0.58767;
  68904. /**
  68905. * Controls the density of each sample
  68906. * @type {number}
  68907. */
  68908. _this.density = 0.926;
  68909. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68910. engine = scene.getEngine();
  68911. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68912. // Configure mesh
  68913. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68914. // Configure
  68915. _this._createPass(scene, ratio.passRatio || ratio);
  68916. _this.onActivate = function (camera) {
  68917. if (!_this.isSupported) {
  68918. _this.dispose(camera);
  68919. }
  68920. _this.onActivate = null;
  68921. };
  68922. _this.onApplyObservable.add(function (effect) {
  68923. _this._updateMeshScreenCoordinates(scene);
  68924. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68925. effect.setFloat("exposure", _this.exposure);
  68926. effect.setFloat("decay", _this.decay);
  68927. effect.setFloat("weight", _this.weight);
  68928. effect.setFloat("density", _this.density);
  68929. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68930. });
  68931. return _this;
  68932. }
  68933. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68934. get: function () {
  68935. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68936. return false;
  68937. },
  68938. set: function (useDiffuseColor) {
  68939. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68940. },
  68941. enumerable: true,
  68942. configurable: true
  68943. });
  68944. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68945. return "VolumetricLightScatteringPostProcess";
  68946. };
  68947. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68948. var mesh = subMesh.getMesh();
  68949. // Render this.mesh as default
  68950. if (mesh === this.mesh && mesh.material) {
  68951. return mesh.material.isReady(mesh);
  68952. }
  68953. var defines = [];
  68954. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68955. var material = subMesh.getMaterial();
  68956. // Alpha test
  68957. if (material) {
  68958. if (material.needAlphaTesting()) {
  68959. defines.push("#define ALPHATEST");
  68960. }
  68961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68962. attribs.push(BABYLON.VertexBuffer.UVKind);
  68963. defines.push("#define UV1");
  68964. }
  68965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68966. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68967. defines.push("#define UV2");
  68968. }
  68969. }
  68970. // Bones
  68971. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68972. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68973. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68975. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68976. }
  68977. else {
  68978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68979. }
  68980. // Instances
  68981. if (useInstances) {
  68982. defines.push("#define INSTANCES");
  68983. attribs.push("world0");
  68984. attribs.push("world1");
  68985. attribs.push("world2");
  68986. attribs.push("world3");
  68987. }
  68988. // Get correct effect
  68989. var join = defines.join("\n");
  68990. if (this._cachedDefines !== join) {
  68991. this._cachedDefines = join;
  68992. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68993. }
  68994. return this._volumetricLightScatteringPass.isReady();
  68995. };
  68996. /**
  68997. * Sets the new light position for light scattering effect
  68998. * @param {BABYLON.Vector3} The new custom light position
  68999. */
  69000. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69001. this.customMeshPosition = position;
  69002. };
  69003. /**
  69004. * Returns the light position for light scattering effect
  69005. * @return {BABYLON.Vector3} The custom light position
  69006. */
  69007. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69008. return this.customMeshPosition;
  69009. };
  69010. /**
  69011. * Disposes the internal assets and detaches the post-process from the camera
  69012. */
  69013. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69014. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69015. if (rttIndex !== -1) {
  69016. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69017. }
  69018. this._volumetricLightScatteringRTT.dispose();
  69019. _super.prototype.dispose.call(this, camera);
  69020. };
  69021. /**
  69022. * Returns the render target texture used by the post-process
  69023. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69024. */
  69025. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69026. return this._volumetricLightScatteringRTT;
  69027. };
  69028. // Private methods
  69029. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69030. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69031. return true;
  69032. }
  69033. return false;
  69034. };
  69035. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69036. var _this = this;
  69037. var engine = scene.getEngine();
  69038. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69039. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69040. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69041. this._volumetricLightScatteringRTT.renderList = null;
  69042. this._volumetricLightScatteringRTT.renderParticles = false;
  69043. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69044. var camera = this.getCamera();
  69045. if (camera) {
  69046. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69047. }
  69048. else {
  69049. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69050. }
  69051. // Custom render function for submeshes
  69052. var renderSubMesh = function (subMesh) {
  69053. var mesh = subMesh.getRenderingMesh();
  69054. if (_this._meshExcluded(mesh)) {
  69055. return;
  69056. }
  69057. var material = subMesh.getMaterial();
  69058. if (!material) {
  69059. return;
  69060. }
  69061. var scene = mesh.getScene();
  69062. var engine = scene.getEngine();
  69063. // Culling
  69064. engine.setState(material.backFaceCulling);
  69065. // Managing instances
  69066. var batch = mesh._getInstancesRenderList(subMesh._id);
  69067. if (batch.mustReturn) {
  69068. return;
  69069. }
  69070. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69071. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69072. var effect = _this._volumetricLightScatteringPass;
  69073. if (mesh === _this.mesh) {
  69074. if (subMesh.effect) {
  69075. effect = subMesh.effect;
  69076. }
  69077. else {
  69078. effect = material.getEffect();
  69079. }
  69080. }
  69081. engine.enableEffect(effect);
  69082. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69083. if (mesh === _this.mesh) {
  69084. material.bind(mesh.getWorldMatrix(), mesh);
  69085. }
  69086. else {
  69087. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69088. // Alpha test
  69089. if (material && material.needAlphaTesting()) {
  69090. var alphaTexture = material.getAlphaTestTexture();
  69091. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69092. if (alphaTexture) {
  69093. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69094. }
  69095. }
  69096. // Bones
  69097. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69098. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69099. }
  69100. }
  69101. // Draw
  69102. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69103. }
  69104. };
  69105. // Render target texture callbacks
  69106. var savedSceneClearColor;
  69107. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69108. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69109. savedSceneClearColor = scene.clearColor;
  69110. scene.clearColor = sceneClearColor;
  69111. });
  69112. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69113. scene.clearColor = savedSceneClearColor;
  69114. });
  69115. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69116. var engine = scene.getEngine();
  69117. var index;
  69118. if (depthOnlySubMeshes.length) {
  69119. engine.setColorWrite(false);
  69120. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69121. renderSubMesh(depthOnlySubMeshes.data[index]);
  69122. }
  69123. engine.setColorWrite(true);
  69124. }
  69125. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69126. renderSubMesh(opaqueSubMeshes.data[index]);
  69127. }
  69128. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69129. renderSubMesh(alphaTestSubMeshes.data[index]);
  69130. }
  69131. if (transparentSubMeshes.length) {
  69132. // Sort sub meshes
  69133. for (index = 0; index < transparentSubMeshes.length; index++) {
  69134. var submesh = transparentSubMeshes.data[index];
  69135. var boundingInfo = submesh.getBoundingInfo();
  69136. if (boundingInfo && scene.activeCamera) {
  69137. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69138. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69139. }
  69140. }
  69141. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69142. sortedArray.sort(function (a, b) {
  69143. // Alpha index first
  69144. if (a._alphaIndex > b._alphaIndex) {
  69145. return 1;
  69146. }
  69147. if (a._alphaIndex < b._alphaIndex) {
  69148. return -1;
  69149. }
  69150. // Then distance to camera
  69151. if (a._distanceToCamera < b._distanceToCamera) {
  69152. return 1;
  69153. }
  69154. if (a._distanceToCamera > b._distanceToCamera) {
  69155. return -1;
  69156. }
  69157. return 0;
  69158. });
  69159. // Render sub meshes
  69160. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69161. for (index = 0; index < sortedArray.length; index++) {
  69162. renderSubMesh(sortedArray[index]);
  69163. }
  69164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69165. }
  69166. };
  69167. };
  69168. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69169. var transform = scene.getTransformMatrix();
  69170. var meshPosition;
  69171. if (this.useCustomMeshPosition) {
  69172. meshPosition = this.customMeshPosition;
  69173. }
  69174. else if (this.attachedNode) {
  69175. meshPosition = this.attachedNode.position;
  69176. }
  69177. else {
  69178. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69179. }
  69180. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69181. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69182. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69183. if (this.invert)
  69184. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69185. };
  69186. // Static methods
  69187. /**
  69188. * Creates a default mesh for the Volumeric Light Scattering post-process
  69189. * @param {string} The mesh name
  69190. * @param {BABYLON.Scene} The scene where to create the mesh
  69191. * @return {BABYLON.Mesh} the default mesh
  69192. */
  69193. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69194. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69195. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69196. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69197. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69198. mesh.material = material;
  69199. return mesh;
  69200. };
  69201. __decorate([
  69202. BABYLON.serializeAsVector3()
  69203. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69204. __decorate([
  69205. BABYLON.serialize()
  69206. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69207. __decorate([
  69208. BABYLON.serialize()
  69209. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69210. __decorate([
  69211. BABYLON.serializeAsMeshReference()
  69212. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69213. __decorate([
  69214. BABYLON.serialize()
  69215. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69216. __decorate([
  69217. BABYLON.serialize()
  69218. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69219. __decorate([
  69220. BABYLON.serialize()
  69221. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69222. __decorate([
  69223. BABYLON.serialize()
  69224. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69225. __decorate([
  69226. BABYLON.serialize()
  69227. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69228. return VolumetricLightScatteringPostProcess;
  69229. }(BABYLON.PostProcess));
  69230. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69231. })(BABYLON || (BABYLON = {}));
  69232. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69233. //
  69234. // This post-process allows the modification of rendered colors by using
  69235. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69236. //
  69237. // The object needs to be provided an url to a texture containing the color
  69238. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69239. // Use an image editing software to tweak the LUT to match your needs.
  69240. //
  69241. // For an example of a color LUT, see here:
  69242. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69243. // For explanations on color grading, see here:
  69244. // http://udn.epicgames.com/Three/ColorGrading.html
  69245. //
  69246. var BABYLON;
  69247. (function (BABYLON) {
  69248. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69249. __extends(ColorCorrectionPostProcess, _super);
  69250. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69251. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69252. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69253. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69254. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69255. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69256. _this.onApply = function (effect) {
  69257. effect.setTexture("colorTable", _this._colorTableTexture);
  69258. };
  69259. return _this;
  69260. }
  69261. return ColorCorrectionPostProcess;
  69262. }(BABYLON.PostProcess));
  69263. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69264. })(BABYLON || (BABYLON = {}));
  69265. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69266. var BABYLON;
  69267. (function (BABYLON) {
  69268. var TonemappingOperator;
  69269. (function (TonemappingOperator) {
  69270. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69271. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69272. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69273. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69274. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69275. ;
  69276. var TonemapPostProcess = /** @class */ (function (_super) {
  69277. __extends(TonemapPostProcess, _super);
  69278. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69280. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69281. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69282. _this._operator = _operator;
  69283. _this.exposureAdjustment = exposureAdjustment;
  69284. var defines = "#define ";
  69285. if (_this._operator === TonemappingOperator.Hable)
  69286. defines += "HABLE_TONEMAPPING";
  69287. else if (_this._operator === TonemappingOperator.Reinhard)
  69288. defines += "REINHARD_TONEMAPPING";
  69289. else if (_this._operator === TonemappingOperator.HejiDawson)
  69290. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69291. else if (_this._operator === TonemappingOperator.Photographic)
  69292. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69293. //sadly a second call to create the effect.
  69294. _this.updateEffect(defines);
  69295. _this.onApply = function (effect) {
  69296. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69297. };
  69298. return _this;
  69299. }
  69300. return TonemapPostProcess;
  69301. }(BABYLON.PostProcess));
  69302. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69303. })(BABYLON || (BABYLON = {}));
  69304. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69305. var BABYLON;
  69306. (function (BABYLON) {
  69307. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69308. __extends(DisplayPassPostProcess, _super);
  69309. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69310. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69311. }
  69312. return DisplayPassPostProcess;
  69313. }(BABYLON.PostProcess));
  69314. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69315. })(BABYLON || (BABYLON = {}));
  69316. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69317. var BABYLON;
  69318. (function (BABYLON) {
  69319. var HighlightsPostProcess = /** @class */ (function (_super) {
  69320. __extends(HighlightsPostProcess, _super);
  69321. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69322. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69323. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69324. }
  69325. return HighlightsPostProcess;
  69326. }(BABYLON.PostProcess));
  69327. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69328. })(BABYLON || (BABYLON = {}));
  69329. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69330. var BABYLON;
  69331. (function (BABYLON) {
  69332. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69333. __extends(ImageProcessingPostProcess, _super);
  69334. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69335. if (camera === void 0) { camera = null; }
  69336. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69337. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69338. _this._fromLinearSpace = true;
  69339. /**
  69340. * Defines cache preventing GC.
  69341. */
  69342. _this._defines = {
  69343. IMAGEPROCESSING: false,
  69344. VIGNETTE: false,
  69345. VIGNETTEBLENDMODEMULTIPLY: false,
  69346. VIGNETTEBLENDMODEOPAQUE: false,
  69347. TONEMAPPING: false,
  69348. CONTRAST: false,
  69349. COLORCURVES: false,
  69350. COLORGRADING: false,
  69351. COLORGRADING3D: false,
  69352. FROMLINEARSPACE: false,
  69353. SAMPLER3DGREENDEPTH: false,
  69354. SAMPLER3DBGRMAP: false,
  69355. IMAGEPROCESSINGPOSTPROCESS: false,
  69356. EXPOSURE: false,
  69357. GRAIN: false,
  69358. };
  69359. // Setup the configuration as forced by the constructor. This would then not force the
  69360. // scene materials output in linear space and let untouched the default forward pass.
  69361. if (imageProcessingConfiguration) {
  69362. imageProcessingConfiguration.applyByPostProcess = true;
  69363. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69364. // This will cause the shader to be compiled
  69365. _this.fromLinearSpace = false;
  69366. }
  69367. else {
  69368. _this._attachImageProcessingConfiguration(null, true);
  69369. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69370. }
  69371. _this.onApply = function (effect) {
  69372. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69373. };
  69374. return _this;
  69375. }
  69376. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69377. /**
  69378. * Gets the image processing configuration used either in this material.
  69379. */
  69380. get: function () {
  69381. return this._imageProcessingConfiguration;
  69382. },
  69383. /**
  69384. * Sets the Default image processing configuration used either in the this material.
  69385. *
  69386. * If sets to null, the scene one is in use.
  69387. */
  69388. set: function (value) {
  69389. this._attachImageProcessingConfiguration(value);
  69390. },
  69391. enumerable: true,
  69392. configurable: true
  69393. });
  69394. /**
  69395. * Attaches a new image processing configuration to the PBR Material.
  69396. * @param configuration
  69397. */
  69398. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69399. var _this = this;
  69400. if (doNotBuild === void 0) { doNotBuild = false; }
  69401. if (configuration === this._imageProcessingConfiguration) {
  69402. return;
  69403. }
  69404. // Detaches observer.
  69405. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69406. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69407. }
  69408. // Pick the scene configuration if needed.
  69409. if (!configuration) {
  69410. var scene = null;
  69411. var engine = this.getEngine();
  69412. var camera = this.getCamera();
  69413. if (camera) {
  69414. scene = camera.getScene();
  69415. }
  69416. else if (engine && engine.scenes) {
  69417. var scenes = engine.scenes;
  69418. scene = scenes[scenes.length - 1];
  69419. }
  69420. else {
  69421. scene = BABYLON.Engine.LastCreatedScene;
  69422. }
  69423. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69424. }
  69425. else {
  69426. this._imageProcessingConfiguration = configuration;
  69427. }
  69428. // Attaches observer.
  69429. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69430. _this._updateParameters();
  69431. });
  69432. // Ensure the effect will be rebuilt.
  69433. if (!doNotBuild) {
  69434. this._updateParameters();
  69435. }
  69436. };
  69437. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69438. /**
  69439. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69440. */
  69441. get: function () {
  69442. return this.imageProcessingConfiguration.colorCurves;
  69443. },
  69444. /**
  69445. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69446. */
  69447. set: function (value) {
  69448. this.imageProcessingConfiguration.colorCurves = value;
  69449. },
  69450. enumerable: true,
  69451. configurable: true
  69452. });
  69453. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69454. /**
  69455. * Gets wether the color curves effect is enabled.
  69456. */
  69457. get: function () {
  69458. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69459. },
  69460. /**
  69461. * Sets wether the color curves effect is enabled.
  69462. */
  69463. set: function (value) {
  69464. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69465. },
  69466. enumerable: true,
  69467. configurable: true
  69468. });
  69469. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69470. /**
  69471. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69472. */
  69473. get: function () {
  69474. return this.imageProcessingConfiguration.colorGradingTexture;
  69475. },
  69476. /**
  69477. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69478. */
  69479. set: function (value) {
  69480. this.imageProcessingConfiguration.colorGradingTexture = value;
  69481. },
  69482. enumerable: true,
  69483. configurable: true
  69484. });
  69485. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69486. /**
  69487. * Gets wether the color grading effect is enabled.
  69488. */
  69489. get: function () {
  69490. return this.imageProcessingConfiguration.colorGradingEnabled;
  69491. },
  69492. /**
  69493. * Gets wether the color grading effect is enabled.
  69494. */
  69495. set: function (value) {
  69496. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69497. },
  69498. enumerable: true,
  69499. configurable: true
  69500. });
  69501. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69502. /**
  69503. * Gets exposure used in the effect.
  69504. */
  69505. get: function () {
  69506. return this.imageProcessingConfiguration.exposure;
  69507. },
  69508. /**
  69509. * Sets exposure used in the effect.
  69510. */
  69511. set: function (value) {
  69512. this.imageProcessingConfiguration.exposure = value;
  69513. },
  69514. enumerable: true,
  69515. configurable: true
  69516. });
  69517. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69518. /**
  69519. * Gets wether tonemapping is enabled or not.
  69520. */
  69521. get: function () {
  69522. return this._imageProcessingConfiguration.toneMappingEnabled;
  69523. },
  69524. /**
  69525. * Sets wether tonemapping is enabled or not
  69526. */
  69527. set: function (value) {
  69528. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69529. },
  69530. enumerable: true,
  69531. configurable: true
  69532. });
  69533. ;
  69534. ;
  69535. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69536. /**
  69537. * Gets contrast used in the effect.
  69538. */
  69539. get: function () {
  69540. return this.imageProcessingConfiguration.contrast;
  69541. },
  69542. /**
  69543. * Sets contrast used in the effect.
  69544. */
  69545. set: function (value) {
  69546. this.imageProcessingConfiguration.contrast = value;
  69547. },
  69548. enumerable: true,
  69549. configurable: true
  69550. });
  69551. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69552. /**
  69553. * Gets Vignette stretch size.
  69554. */
  69555. get: function () {
  69556. return this.imageProcessingConfiguration.vignetteStretch;
  69557. },
  69558. /**
  69559. * Sets Vignette stretch size.
  69560. */
  69561. set: function (value) {
  69562. this.imageProcessingConfiguration.vignetteStretch = value;
  69563. },
  69564. enumerable: true,
  69565. configurable: true
  69566. });
  69567. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69568. /**
  69569. * Gets Vignette centre X Offset.
  69570. */
  69571. get: function () {
  69572. return this.imageProcessingConfiguration.vignetteCentreX;
  69573. },
  69574. /**
  69575. * Sets Vignette centre X Offset.
  69576. */
  69577. set: function (value) {
  69578. this.imageProcessingConfiguration.vignetteCentreX = value;
  69579. },
  69580. enumerable: true,
  69581. configurable: true
  69582. });
  69583. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69584. /**
  69585. * Gets Vignette centre Y Offset.
  69586. */
  69587. get: function () {
  69588. return this.imageProcessingConfiguration.vignetteCentreY;
  69589. },
  69590. /**
  69591. * Sets Vignette centre Y Offset.
  69592. */
  69593. set: function (value) {
  69594. this.imageProcessingConfiguration.vignetteCentreY = value;
  69595. },
  69596. enumerable: true,
  69597. configurable: true
  69598. });
  69599. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69600. /**
  69601. * Gets Vignette weight or intensity of the vignette effect.
  69602. */
  69603. get: function () {
  69604. return this.imageProcessingConfiguration.vignetteWeight;
  69605. },
  69606. /**
  69607. * Sets Vignette weight or intensity of the vignette effect.
  69608. */
  69609. set: function (value) {
  69610. this.imageProcessingConfiguration.vignetteWeight = value;
  69611. },
  69612. enumerable: true,
  69613. configurable: true
  69614. });
  69615. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69616. /**
  69617. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69618. * if vignetteEnabled is set to true.
  69619. */
  69620. get: function () {
  69621. return this.imageProcessingConfiguration.vignetteColor;
  69622. },
  69623. /**
  69624. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69625. * if vignetteEnabled is set to true.
  69626. */
  69627. set: function (value) {
  69628. this.imageProcessingConfiguration.vignetteColor = value;
  69629. },
  69630. enumerable: true,
  69631. configurable: true
  69632. });
  69633. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69634. /**
  69635. * Gets Camera field of view used by the Vignette effect.
  69636. */
  69637. get: function () {
  69638. return this.imageProcessingConfiguration.vignetteCameraFov;
  69639. },
  69640. /**
  69641. * Sets Camera field of view used by the Vignette effect.
  69642. */
  69643. set: function (value) {
  69644. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69645. },
  69646. enumerable: true,
  69647. configurable: true
  69648. });
  69649. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69650. /**
  69651. * Gets the vignette blend mode allowing different kind of effect.
  69652. */
  69653. get: function () {
  69654. return this.imageProcessingConfiguration.vignetteBlendMode;
  69655. },
  69656. /**
  69657. * Sets the vignette blend mode allowing different kind of effect.
  69658. */
  69659. set: function (value) {
  69660. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69661. },
  69662. enumerable: true,
  69663. configurable: true
  69664. });
  69665. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69666. /**
  69667. * Gets wether the vignette effect is enabled.
  69668. */
  69669. get: function () {
  69670. return this.imageProcessingConfiguration.vignetteEnabled;
  69671. },
  69672. /**
  69673. * Sets wether the vignette effect is enabled.
  69674. */
  69675. set: function (value) {
  69676. this.imageProcessingConfiguration.vignetteEnabled = value;
  69677. },
  69678. enumerable: true,
  69679. configurable: true
  69680. });
  69681. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69682. /**
  69683. * Gets wether the input of the processing is in Gamma or Linear Space.
  69684. */
  69685. get: function () {
  69686. return this._fromLinearSpace;
  69687. },
  69688. /**
  69689. * Sets wether the input of the processing is in Gamma or Linear Space.
  69690. */
  69691. set: function (value) {
  69692. if (this._fromLinearSpace === value) {
  69693. return;
  69694. }
  69695. this._fromLinearSpace = value;
  69696. this._updateParameters();
  69697. },
  69698. enumerable: true,
  69699. configurable: true
  69700. });
  69701. ImageProcessingPostProcess.prototype.getClassName = function () {
  69702. return "ImageProcessingPostProcess";
  69703. };
  69704. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69705. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69706. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69707. var defines = "";
  69708. for (var define in this._defines) {
  69709. if (this._defines[define]) {
  69710. defines += "#define " + define + ";\r\n";
  69711. }
  69712. }
  69713. var samplers = ["textureSampler"];
  69714. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69715. var uniforms = ["scale"];
  69716. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69717. this.updateEffect(defines, uniforms, samplers);
  69718. };
  69719. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69720. _super.prototype.dispose.call(this, camera);
  69721. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69722. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69723. }
  69724. this.imageProcessingConfiguration.applyByPostProcess = false;
  69725. };
  69726. __decorate([
  69727. BABYLON.serialize()
  69728. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69729. return ImageProcessingPostProcess;
  69730. }(BABYLON.PostProcess));
  69731. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69732. })(BABYLON || (BABYLON = {}));
  69733. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69734. var BABYLON;
  69735. (function (BABYLON) {
  69736. /**
  69737. * The Blur Post Process which blurs an image based on a kernel and direction.
  69738. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69739. */
  69740. var BlurPostProcess = /** @class */ (function (_super) {
  69741. __extends(BlurPostProcess, _super);
  69742. /**
  69743. * Creates a new instance of @see BlurPostProcess
  69744. * @param name The name of the effect.
  69745. * @param direction The direction in which to blur the image.
  69746. * @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.
  69747. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69748. * @param camera The camera to apply the render pass to.
  69749. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69750. * @param engine The engine which the post process will be applied. (default: current engine)
  69751. * @param reusable If the post process can be reused on the same frame. (default: false)
  69752. * @param textureType Type of textures used when performing the post process. (default: 0)
  69753. */
  69754. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69756. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69757. if (defines === void 0) { defines = ""; }
  69758. 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;
  69759. _this.direction = direction;
  69760. _this._packedFloat = false;
  69761. _this._staticDefines = "";
  69762. _this._staticDefines = defines;
  69763. _this.onApplyObservable.add(function (effect) {
  69764. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69765. });
  69766. _this.kernel = kernel;
  69767. return _this;
  69768. }
  69769. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69770. /**
  69771. * Gets the length in pixels of the blur sample region
  69772. */
  69773. get: function () {
  69774. return this._idealKernel;
  69775. },
  69776. /**
  69777. * Sets the length in pixels of the blur sample region
  69778. */
  69779. set: function (v) {
  69780. if (this._idealKernel === v) {
  69781. return;
  69782. }
  69783. v = Math.max(v, 1);
  69784. this._idealKernel = v;
  69785. this._kernel = this._nearestBestKernel(v);
  69786. this._updateParameters();
  69787. },
  69788. enumerable: true,
  69789. configurable: true
  69790. });
  69791. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69792. /**
  69793. * Gets wether or not the blur is unpacking/repacking floats
  69794. */
  69795. get: function () {
  69796. return this._packedFloat;
  69797. },
  69798. /**
  69799. * Sets wether or not the blur needs to unpack/repack floats
  69800. */
  69801. set: function (v) {
  69802. if (this._packedFloat === v) {
  69803. return;
  69804. }
  69805. this._packedFloat = v;
  69806. this._updateParameters();
  69807. },
  69808. enumerable: true,
  69809. configurable: true
  69810. });
  69811. BlurPostProcess.prototype._updateParameters = function () {
  69812. // Generate sampling offsets and weights
  69813. var N = this._kernel;
  69814. var centerIndex = (N - 1) / 2;
  69815. // Generate Gaussian sampling weights over kernel
  69816. var offsets = [];
  69817. var weights = [];
  69818. var totalWeight = 0;
  69819. for (var i = 0; i < N; i++) {
  69820. var u = i / (N - 1);
  69821. var w = this._gaussianWeight(u * 2.0 - 1);
  69822. offsets[i] = (i - centerIndex);
  69823. weights[i] = w;
  69824. totalWeight += w;
  69825. }
  69826. // Normalize weights
  69827. for (var i = 0; i < weights.length; i++) {
  69828. weights[i] /= totalWeight;
  69829. }
  69830. // Optimize: combine samples to take advantage of hardware linear sampling
  69831. // Walk from left to center, combining pairs (symmetrically)
  69832. var linearSamplingWeights = [];
  69833. var linearSamplingOffsets = [];
  69834. var linearSamplingMap = [];
  69835. for (var i = 0; i <= centerIndex; i += 2) {
  69836. var j = Math.min(i + 1, Math.floor(centerIndex));
  69837. var singleCenterSample = i === j;
  69838. if (singleCenterSample) {
  69839. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69840. }
  69841. else {
  69842. var sharedCell = j === centerIndex;
  69843. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69844. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69845. if (offsetLinear === 0) {
  69846. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69847. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69848. }
  69849. else {
  69850. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69851. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69852. }
  69853. }
  69854. }
  69855. for (var i = 0; i < linearSamplingMap.length; i++) {
  69856. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69857. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69858. }
  69859. // Replace with optimized
  69860. offsets = linearSamplingOffsets;
  69861. weights = linearSamplingWeights;
  69862. // Generate shaders
  69863. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69864. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69865. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69866. var defines = "";
  69867. defines += this._staticDefines;
  69868. for (var i = 0; i < varyingCount; i++) {
  69869. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69870. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69871. }
  69872. var depCount = 0;
  69873. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69874. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69875. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69876. depCount++;
  69877. }
  69878. if (this.packedFloat) {
  69879. defines += "#define PACKEDFLOAT 1";
  69880. }
  69881. this.updateEffect(defines, null, null, {
  69882. varyingCount: varyingCount,
  69883. depCount: depCount
  69884. });
  69885. };
  69886. /**
  69887. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69888. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69889. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69890. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69891. * The gaps between physical kernels are compensated for in the weighting of the samples
  69892. * @param idealKernel Ideal blur kernel.
  69893. * @return Nearest best kernel.
  69894. */
  69895. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69896. var v = Math.round(idealKernel);
  69897. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69898. var k = _a[_i];
  69899. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69900. return Math.max(k, 3);
  69901. }
  69902. }
  69903. return Math.max(v, 3);
  69904. };
  69905. /**
  69906. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69907. * @param x The point on the Gaussian distribution to sample.
  69908. * @return the value of the Gaussian function at x.
  69909. */
  69910. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69911. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69912. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69913. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69914. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69915. // truncated at around 1.3% of peak strength.
  69916. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69917. var sigma = (1 / 3);
  69918. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69919. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69920. var weight = (1.0 / denominator) * Math.exp(exponent);
  69921. return weight;
  69922. };
  69923. /**
  69924. * Generates a string that can be used as a floating point number in GLSL.
  69925. * @param x Value to print.
  69926. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69927. * @return GLSL float string.
  69928. */
  69929. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69930. if (decimalFigures === void 0) { decimalFigures = 8; }
  69931. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69932. };
  69933. return BlurPostProcess;
  69934. }(BABYLON.PostProcess));
  69935. BABYLON.BlurPostProcess = BlurPostProcess;
  69936. })(BABYLON || (BABYLON = {}));
  69937. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69938. var BABYLON;
  69939. (function (BABYLON) {
  69940. var Bone = /** @class */ (function (_super) {
  69941. __extends(Bone, _super);
  69942. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69943. if (parentBone === void 0) { parentBone = null; }
  69944. if (localMatrix === void 0) { localMatrix = null; }
  69945. if (restPose === void 0) { restPose = null; }
  69946. if (baseMatrix === void 0) { baseMatrix = null; }
  69947. if (index === void 0) { index = null; }
  69948. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69949. _this.name = name;
  69950. _this.children = new Array();
  69951. _this.animations = new Array();
  69952. // Set this value to map this bone to a different index in the transform matrices.
  69953. // Set this value to -1 to exclude the bone from the transform matrices.
  69954. _this._index = null;
  69955. _this._worldTransform = new BABYLON.Matrix();
  69956. _this._absoluteTransform = new BABYLON.Matrix();
  69957. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69958. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69959. _this._scaleVector = BABYLON.Vector3.One();
  69960. _this._negateScaleChildren = BABYLON.Vector3.One();
  69961. _this._scalingDeterminant = 1;
  69962. _this._skeleton = skeleton;
  69963. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69964. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69965. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69966. _this._index = index;
  69967. skeleton.bones.push(_this);
  69968. _this.setParent(parentBone, false);
  69969. _this._updateDifferenceMatrix();
  69970. return _this;
  69971. }
  69972. Object.defineProperty(Bone.prototype, "_matrix", {
  69973. get: function () {
  69974. return this._localMatrix;
  69975. },
  69976. set: function (val) {
  69977. if (this._localMatrix) {
  69978. this._localMatrix.copyFrom(val);
  69979. }
  69980. else {
  69981. this._localMatrix = val;
  69982. }
  69983. },
  69984. enumerable: true,
  69985. configurable: true
  69986. });
  69987. // Members
  69988. Bone.prototype.getSkeleton = function () {
  69989. return this._skeleton;
  69990. };
  69991. Bone.prototype.getParent = function () {
  69992. return this._parent;
  69993. };
  69994. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69995. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69996. if (this._parent === parent) {
  69997. return;
  69998. }
  69999. if (this._parent) {
  70000. var index = this._parent.children.indexOf(this);
  70001. if (index !== -1) {
  70002. this._parent.children.splice(index, 1);
  70003. }
  70004. }
  70005. this._parent = parent;
  70006. if (this._parent) {
  70007. this._parent.children.push(this);
  70008. }
  70009. if (updateDifferenceMatrix) {
  70010. this._updateDifferenceMatrix();
  70011. }
  70012. };
  70013. Bone.prototype.getLocalMatrix = function () {
  70014. return this._localMatrix;
  70015. };
  70016. Bone.prototype.getBaseMatrix = function () {
  70017. return this._baseMatrix;
  70018. };
  70019. Bone.prototype.getRestPose = function () {
  70020. return this._restPose;
  70021. };
  70022. Bone.prototype.returnToRest = function () {
  70023. this.updateMatrix(this._restPose.clone());
  70024. };
  70025. Bone.prototype.getWorldMatrix = function () {
  70026. return this._worldTransform;
  70027. };
  70028. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70029. return this._invertedAbsoluteTransform;
  70030. };
  70031. Bone.prototype.getAbsoluteTransform = function () {
  70032. return this._absoluteTransform;
  70033. };
  70034. Object.defineProperty(Bone.prototype, "position", {
  70035. // Properties (matches AbstractMesh properties)
  70036. get: function () {
  70037. return this.getPosition();
  70038. },
  70039. set: function (newPosition) {
  70040. this.setPosition(newPosition);
  70041. },
  70042. enumerable: true,
  70043. configurable: true
  70044. });
  70045. Object.defineProperty(Bone.prototype, "rotation", {
  70046. get: function () {
  70047. return this.getRotation();
  70048. },
  70049. set: function (newRotation) {
  70050. this.setRotation(newRotation);
  70051. },
  70052. enumerable: true,
  70053. configurable: true
  70054. });
  70055. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70056. get: function () {
  70057. return this.getRotationQuaternion();
  70058. },
  70059. set: function (newRotation) {
  70060. this.setRotationQuaternion(newRotation);
  70061. },
  70062. enumerable: true,
  70063. configurable: true
  70064. });
  70065. Object.defineProperty(Bone.prototype, "scaling", {
  70066. get: function () {
  70067. return this.getScale();
  70068. },
  70069. set: function (newScaling) {
  70070. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70071. },
  70072. enumerable: true,
  70073. configurable: true
  70074. });
  70075. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70076. /**
  70077. * Gets the animation properties override
  70078. */
  70079. get: function () {
  70080. return this._skeleton.animationPropertiesOverride;
  70081. },
  70082. enumerable: true,
  70083. configurable: true
  70084. });
  70085. // Methods
  70086. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70087. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70088. this._baseMatrix = matrix.clone();
  70089. this._localMatrix = matrix.clone();
  70090. this._skeleton._markAsDirty();
  70091. if (updateDifferenceMatrix) {
  70092. this._updateDifferenceMatrix();
  70093. }
  70094. };
  70095. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70096. if (!rootMatrix) {
  70097. rootMatrix = this._baseMatrix;
  70098. }
  70099. if (this._parent) {
  70100. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70101. }
  70102. else {
  70103. this._absoluteTransform.copyFrom(rootMatrix);
  70104. }
  70105. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70106. for (var index = 0; index < this.children.length; index++) {
  70107. this.children[index]._updateDifferenceMatrix();
  70108. }
  70109. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70110. };
  70111. Bone.prototype.markAsDirty = function () {
  70112. this._currentRenderId++;
  70113. this._skeleton._markAsDirty();
  70114. };
  70115. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70116. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70117. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70118. // all animation may be coming from a library skeleton, so may need to create animation
  70119. if (this.animations.length === 0) {
  70120. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70121. this.animations[0].setKeys([]);
  70122. }
  70123. // get animation info / verify there is such a range from the source bone
  70124. var sourceRange = source.animations[0].getRange(rangeName);
  70125. if (!sourceRange) {
  70126. return false;
  70127. }
  70128. var from = sourceRange.from;
  70129. var to = sourceRange.to;
  70130. var sourceKeys = source.animations[0].getKeys();
  70131. // rescaling prep
  70132. var sourceBoneLength = source.length;
  70133. var sourceParent = source.getParent();
  70134. var parent = this.getParent();
  70135. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70136. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70137. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70138. var destKeys = this.animations[0].getKeys();
  70139. // loop vars declaration
  70140. var orig;
  70141. var origTranslation;
  70142. var mat;
  70143. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70144. orig = sourceKeys[key];
  70145. if (orig.frame >= from && orig.frame <= to) {
  70146. if (rescaleAsRequired) {
  70147. mat = orig.value.clone();
  70148. // scale based on parent ratio, when bone has parent
  70149. if (parentScalingReqd) {
  70150. origTranslation = mat.getTranslation();
  70151. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70152. // scale based on skeleton dimension ratio when root bone, and value is passed
  70153. }
  70154. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70155. origTranslation = mat.getTranslation();
  70156. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70157. // use original when root bone, and no data for skelDimensionsRatio
  70158. }
  70159. else {
  70160. mat = orig.value;
  70161. }
  70162. }
  70163. else {
  70164. mat = orig.value;
  70165. }
  70166. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70167. }
  70168. }
  70169. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70170. return true;
  70171. };
  70172. /**
  70173. * Translate the bone in local or world space.
  70174. * @param vec The amount to translate the bone.
  70175. * @param space The space that the translation is in.
  70176. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70177. */
  70178. Bone.prototype.translate = function (vec, space, mesh) {
  70179. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70180. var lm = this.getLocalMatrix();
  70181. if (space == BABYLON.Space.LOCAL) {
  70182. lm.m[12] += vec.x;
  70183. lm.m[13] += vec.y;
  70184. lm.m[14] += vec.z;
  70185. }
  70186. else {
  70187. var wm = null;
  70188. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70189. if (mesh) {
  70190. wm = mesh.getWorldMatrix();
  70191. }
  70192. this._skeleton.computeAbsoluteTransforms();
  70193. var tmat = Bone._tmpMats[0];
  70194. var tvec = Bone._tmpVecs[0];
  70195. if (this._parent) {
  70196. if (mesh && wm) {
  70197. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70198. tmat.multiplyToRef(wm, tmat);
  70199. }
  70200. else {
  70201. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70202. }
  70203. }
  70204. tmat.m[12] = 0;
  70205. tmat.m[13] = 0;
  70206. tmat.m[14] = 0;
  70207. tmat.invert();
  70208. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70209. lm.m[12] += tvec.x;
  70210. lm.m[13] += tvec.y;
  70211. lm.m[14] += tvec.z;
  70212. }
  70213. this.markAsDirty();
  70214. };
  70215. /**
  70216. * Set the postion of the bone in local or world space.
  70217. * @param position The position to set the bone.
  70218. * @param space The space that the position is in.
  70219. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70220. */
  70221. Bone.prototype.setPosition = function (position, space, mesh) {
  70222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70223. var lm = this.getLocalMatrix();
  70224. if (space == BABYLON.Space.LOCAL) {
  70225. lm.m[12] = position.x;
  70226. lm.m[13] = position.y;
  70227. lm.m[14] = position.z;
  70228. }
  70229. else {
  70230. var wm = null;
  70231. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70232. if (mesh) {
  70233. wm = mesh.getWorldMatrix();
  70234. }
  70235. this._skeleton.computeAbsoluteTransforms();
  70236. var tmat = Bone._tmpMats[0];
  70237. var vec = Bone._tmpVecs[0];
  70238. if (this._parent) {
  70239. if (mesh && wm) {
  70240. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70241. tmat.multiplyToRef(wm, tmat);
  70242. }
  70243. else {
  70244. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70245. }
  70246. }
  70247. tmat.invert();
  70248. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70249. lm.m[12] = vec.x;
  70250. lm.m[13] = vec.y;
  70251. lm.m[14] = vec.z;
  70252. }
  70253. this.markAsDirty();
  70254. };
  70255. /**
  70256. * Set the absolute postion of the bone (world space).
  70257. * @param position The position to set the bone.
  70258. * @param mesh The mesh that this bone is attached to.
  70259. */
  70260. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70261. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70262. };
  70263. /**
  70264. * Set the scale of the bone on the x, y and z axes.
  70265. * @param x The scale of the bone on the x axis.
  70266. * @param x The scale of the bone on the y axis.
  70267. * @param z The scale of the bone on the z axis.
  70268. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70269. */
  70270. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70271. if (scaleChildren === void 0) { scaleChildren = false; }
  70272. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70273. if (!scaleChildren) {
  70274. this._negateScaleChildren.x = 1 / x;
  70275. this._negateScaleChildren.y = 1 / y;
  70276. this._negateScaleChildren.z = 1 / z;
  70277. }
  70278. this._syncScaleVector();
  70279. }
  70280. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70281. };
  70282. /**
  70283. * Scale the bone on the x, y and z axes.
  70284. * @param x The amount to scale the bone on the x axis.
  70285. * @param x The amount to scale the bone on the y axis.
  70286. * @param z The amount to scale the bone on the z axis.
  70287. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70288. */
  70289. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70290. if (scaleChildren === void 0) { scaleChildren = false; }
  70291. var locMat = this.getLocalMatrix();
  70292. var origLocMat = Bone._tmpMats[0];
  70293. origLocMat.copyFrom(locMat);
  70294. var origLocMatInv = Bone._tmpMats[1];
  70295. origLocMatInv.copyFrom(origLocMat);
  70296. origLocMatInv.invert();
  70297. var scaleMat = Bone._tmpMats[2];
  70298. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70299. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70300. this._scaleVector.x *= x;
  70301. this._scaleVector.y *= y;
  70302. this._scaleVector.z *= z;
  70303. locMat.multiplyToRef(origLocMatInv, locMat);
  70304. locMat.multiplyToRef(scaleMat, locMat);
  70305. locMat.multiplyToRef(origLocMat, locMat);
  70306. var parent = this.getParent();
  70307. if (parent) {
  70308. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70309. }
  70310. else {
  70311. this.getAbsoluteTransform().copyFrom(locMat);
  70312. }
  70313. var len = this.children.length;
  70314. scaleMat.invert();
  70315. for (var i = 0; i < len; i++) {
  70316. var child = this.children[i];
  70317. var cm = child.getLocalMatrix();
  70318. cm.multiplyToRef(scaleMat, cm);
  70319. var lm = child.getLocalMatrix();
  70320. lm.m[12] *= x;
  70321. lm.m[13] *= y;
  70322. lm.m[14] *= z;
  70323. }
  70324. this.computeAbsoluteTransforms();
  70325. if (scaleChildren) {
  70326. for (var i = 0; i < len; i++) {
  70327. this.children[i].scale(x, y, z, scaleChildren);
  70328. }
  70329. }
  70330. this.markAsDirty();
  70331. };
  70332. /**
  70333. * Set the yaw, pitch, and roll of the bone in local or world space.
  70334. * @param yaw The rotation of the bone on the y axis.
  70335. * @param pitch The rotation of the bone on the x axis.
  70336. * @param roll The rotation of the bone on the z axis.
  70337. * @param space The space that the axes of rotation are in.
  70338. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70339. */
  70340. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70342. var rotMat = Bone._tmpMats[0];
  70343. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70344. var rotMatInv = Bone._tmpMats[1];
  70345. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70346. rotMatInv.multiplyToRef(rotMat, rotMat);
  70347. this._rotateWithMatrix(rotMat, space, mesh);
  70348. };
  70349. /**
  70350. * Rotate the bone on an axis in local or world space.
  70351. * @param axis The axis to rotate the bone on.
  70352. * @param amount The amount to rotate the bone.
  70353. * @param space The space that the axis is in.
  70354. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70355. */
  70356. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70357. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70358. var rmat = Bone._tmpMats[0];
  70359. rmat.m[12] = 0;
  70360. rmat.m[13] = 0;
  70361. rmat.m[14] = 0;
  70362. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70363. this._rotateWithMatrix(rmat, space, mesh);
  70364. };
  70365. /**
  70366. * Set the rotation of the bone to a particular axis angle in local or world space.
  70367. * @param axis The axis to rotate the bone on.
  70368. * @param angle The angle that the bone should be rotated to.
  70369. * @param space The space that the axis is in.
  70370. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70371. */
  70372. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70374. var rotMat = Bone._tmpMats[0];
  70375. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70376. var rotMatInv = Bone._tmpMats[1];
  70377. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70378. rotMatInv.multiplyToRef(rotMat, rotMat);
  70379. this._rotateWithMatrix(rotMat, space, mesh);
  70380. };
  70381. /**
  70382. * Set the euler rotation of the bone in local of world space.
  70383. * @param rotation The euler rotation that the bone should be set to.
  70384. * @param space The space that the rotation is in.
  70385. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70386. */
  70387. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70388. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70389. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70390. };
  70391. /**
  70392. * Set the quaternion rotation of the bone in local of world space.
  70393. * @param quat The quaternion rotation that the bone should be set to.
  70394. * @param space The space that the rotation is in.
  70395. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70396. */
  70397. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70398. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70399. var rotMatInv = Bone._tmpMats[0];
  70400. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70401. var rotMat = Bone._tmpMats[1];
  70402. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70403. rotMatInv.multiplyToRef(rotMat, rotMat);
  70404. this._rotateWithMatrix(rotMat, space, mesh);
  70405. };
  70406. /**
  70407. * Set the rotation matrix of the bone in local of world space.
  70408. * @param rotMat The rotation matrix that the bone should be set to.
  70409. * @param space The space that the rotation is in.
  70410. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70411. */
  70412. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70414. var rotMatInv = Bone._tmpMats[0];
  70415. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70416. var rotMat2 = Bone._tmpMats[1];
  70417. rotMat2.copyFrom(rotMat);
  70418. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70419. this._rotateWithMatrix(rotMat2, space, mesh);
  70420. };
  70421. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70423. var lmat = this.getLocalMatrix();
  70424. var lx = lmat.m[12];
  70425. var ly = lmat.m[13];
  70426. var lz = lmat.m[14];
  70427. var parent = this.getParent();
  70428. var parentScale = Bone._tmpMats[3];
  70429. var parentScaleInv = Bone._tmpMats[4];
  70430. if (parent) {
  70431. if (space == BABYLON.Space.WORLD) {
  70432. if (mesh) {
  70433. parentScale.copyFrom(mesh.getWorldMatrix());
  70434. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70435. }
  70436. else {
  70437. parentScale.copyFrom(parent.getAbsoluteTransform());
  70438. }
  70439. }
  70440. else {
  70441. parentScale = parent._scaleMatrix;
  70442. }
  70443. parentScaleInv.copyFrom(parentScale);
  70444. parentScaleInv.invert();
  70445. lmat.multiplyToRef(parentScale, lmat);
  70446. lmat.multiplyToRef(rmat, lmat);
  70447. lmat.multiplyToRef(parentScaleInv, lmat);
  70448. }
  70449. else {
  70450. if (space == BABYLON.Space.WORLD && mesh) {
  70451. parentScale.copyFrom(mesh.getWorldMatrix());
  70452. parentScaleInv.copyFrom(parentScale);
  70453. parentScaleInv.invert();
  70454. lmat.multiplyToRef(parentScale, lmat);
  70455. lmat.multiplyToRef(rmat, lmat);
  70456. lmat.multiplyToRef(parentScaleInv, lmat);
  70457. }
  70458. else {
  70459. lmat.multiplyToRef(rmat, lmat);
  70460. }
  70461. }
  70462. lmat.m[12] = lx;
  70463. lmat.m[13] = ly;
  70464. lmat.m[14] = lz;
  70465. this.computeAbsoluteTransforms();
  70466. this.markAsDirty();
  70467. };
  70468. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70470. if (space == BABYLON.Space.WORLD) {
  70471. var scaleMatrix = Bone._tmpMats[2];
  70472. scaleMatrix.copyFrom(this._scaleMatrix);
  70473. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70474. if (mesh) {
  70475. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70476. var meshScale = Bone._tmpMats[3];
  70477. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70478. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70479. }
  70480. rotMatInv.invert();
  70481. scaleMatrix.m[0] *= this._scalingDeterminant;
  70482. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70483. }
  70484. else {
  70485. rotMatInv.copyFrom(this.getLocalMatrix());
  70486. rotMatInv.invert();
  70487. var scaleMatrix = Bone._tmpMats[2];
  70488. scaleMatrix.copyFrom(this._scaleMatrix);
  70489. if (this._parent) {
  70490. var pscaleMatrix = Bone._tmpMats[3];
  70491. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70492. pscaleMatrix.invert();
  70493. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70494. }
  70495. else {
  70496. scaleMatrix.m[0] *= this._scalingDeterminant;
  70497. }
  70498. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70499. }
  70500. };
  70501. /**
  70502. * Get the scale of the bone
  70503. * @returns the scale of the bone
  70504. */
  70505. Bone.prototype.getScale = function () {
  70506. return this._scaleVector.clone();
  70507. };
  70508. /**
  70509. * Copy the scale of the bone to a vector3.
  70510. * @param result The vector3 to copy the scale to
  70511. */
  70512. Bone.prototype.getScaleToRef = function (result) {
  70513. result.copyFrom(this._scaleVector);
  70514. };
  70515. /**
  70516. * Get the position of the bone in local or world space.
  70517. * @param space The space that the returned position is in.
  70518. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70519. * @returns The position of the bone
  70520. */
  70521. Bone.prototype.getPosition = function (space, mesh) {
  70522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70523. if (mesh === void 0) { mesh = null; }
  70524. var pos = BABYLON.Vector3.Zero();
  70525. this.getPositionToRef(space, mesh, pos);
  70526. return pos;
  70527. };
  70528. /**
  70529. * Copy the position of the bone to a vector3 in local or world space.
  70530. * @param space The space that the returned position is in.
  70531. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70532. * @param result The vector3 to copy the position to.
  70533. */
  70534. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70536. if (space == BABYLON.Space.LOCAL) {
  70537. var lm = this.getLocalMatrix();
  70538. result.x = lm.m[12];
  70539. result.y = lm.m[13];
  70540. result.z = lm.m[14];
  70541. }
  70542. else {
  70543. var wm = null;
  70544. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70545. if (mesh) {
  70546. wm = mesh.getWorldMatrix();
  70547. }
  70548. this._skeleton.computeAbsoluteTransforms();
  70549. var tmat = Bone._tmpMats[0];
  70550. if (mesh && wm) {
  70551. tmat.copyFrom(this.getAbsoluteTransform());
  70552. tmat.multiplyToRef(wm, tmat);
  70553. }
  70554. else {
  70555. tmat = this.getAbsoluteTransform();
  70556. }
  70557. result.x = tmat.m[12];
  70558. result.y = tmat.m[13];
  70559. result.z = tmat.m[14];
  70560. }
  70561. };
  70562. /**
  70563. * Get the absolute position of the bone (world space).
  70564. * @param mesh The mesh that this bone is attached to.
  70565. * @returns The absolute position of the bone
  70566. */
  70567. Bone.prototype.getAbsolutePosition = function (mesh) {
  70568. if (mesh === void 0) { mesh = null; }
  70569. var pos = BABYLON.Vector3.Zero();
  70570. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70571. return pos;
  70572. };
  70573. /**
  70574. * Copy the absolute position of the bone (world space) to the result param.
  70575. * @param mesh The mesh that this bone is attached to.
  70576. * @param result The vector3 to copy the absolute position to.
  70577. */
  70578. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70579. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70580. };
  70581. /**
  70582. * Compute the absolute transforms of this bone and its children.
  70583. */
  70584. Bone.prototype.computeAbsoluteTransforms = function () {
  70585. if (this._parent) {
  70586. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70587. }
  70588. else {
  70589. this._absoluteTransform.copyFrom(this._localMatrix);
  70590. var poseMatrix = this._skeleton.getPoseMatrix();
  70591. if (poseMatrix) {
  70592. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70593. }
  70594. }
  70595. var children = this.children;
  70596. var len = children.length;
  70597. for (var i = 0; i < len; i++) {
  70598. children[i].computeAbsoluteTransforms();
  70599. }
  70600. };
  70601. Bone.prototype._syncScaleVector = function () {
  70602. var lm = this.getLocalMatrix();
  70603. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70604. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70605. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70606. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70607. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70608. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70609. this._scaleVector.x = xs * Math.sqrt(xsq);
  70610. this._scaleVector.y = ys * Math.sqrt(ysq);
  70611. this._scaleVector.z = zs * Math.sqrt(zsq);
  70612. if (this._parent) {
  70613. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70614. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70615. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70616. }
  70617. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  70618. };
  70619. /**
  70620. * Get the world direction from an axis that is in the local space of the bone.
  70621. * @param localAxis The local direction that is used to compute the world direction.
  70622. * @param mesh The mesh that this bone is attached to.
  70623. * @returns The world direction
  70624. */
  70625. Bone.prototype.getDirection = function (localAxis, mesh) {
  70626. if (mesh === void 0) { mesh = null; }
  70627. var result = BABYLON.Vector3.Zero();
  70628. this.getDirectionToRef(localAxis, mesh, result);
  70629. return result;
  70630. };
  70631. /**
  70632. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70633. * @param localAxis The local direction that is used to compute the world direction.
  70634. * @param mesh The mesh that this bone is attached to.
  70635. * @param result The vector3 that the world direction will be copied to.
  70636. */
  70637. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70638. if (mesh === void 0) { mesh = null; }
  70639. var wm = null;
  70640. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70641. if (mesh) {
  70642. wm = mesh.getWorldMatrix();
  70643. }
  70644. this._skeleton.computeAbsoluteTransforms();
  70645. var mat = Bone._tmpMats[0];
  70646. mat.copyFrom(this.getAbsoluteTransform());
  70647. if (mesh && wm) {
  70648. mat.multiplyToRef(wm, mat);
  70649. }
  70650. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70651. result.normalize();
  70652. };
  70653. /**
  70654. * Get the euler rotation of the bone in local or world space.
  70655. * @param space The space that the rotation should be in.
  70656. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70657. * @returns The euler rotation
  70658. */
  70659. Bone.prototype.getRotation = function (space, mesh) {
  70660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70661. if (mesh === void 0) { mesh = null; }
  70662. var result = BABYLON.Vector3.Zero();
  70663. this.getRotationToRef(space, mesh, result);
  70664. return result;
  70665. };
  70666. /**
  70667. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70668. * @param space The space that the rotation should be in.
  70669. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70670. * @param result The vector3 that the rotation should be copied to.
  70671. */
  70672. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70673. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70674. if (mesh === void 0) { mesh = null; }
  70675. var quat = Bone._tmpQuat;
  70676. this.getRotationQuaternionToRef(space, mesh, quat);
  70677. quat.toEulerAnglesToRef(result);
  70678. };
  70679. /**
  70680. * Get the quaternion rotation of the bone in either local or world space.
  70681. * @param space The space that the rotation should be in.
  70682. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70683. * @returns The quaternion rotation
  70684. */
  70685. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70687. if (mesh === void 0) { mesh = null; }
  70688. var result = BABYLON.Quaternion.Identity();
  70689. this.getRotationQuaternionToRef(space, mesh, result);
  70690. return result;
  70691. };
  70692. /**
  70693. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70694. * @param space The space that the rotation should be in.
  70695. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70696. * @param result The quaternion that the rotation should be copied to.
  70697. */
  70698. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70700. if (mesh === void 0) { mesh = null; }
  70701. if (space == BABYLON.Space.LOCAL) {
  70702. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70703. }
  70704. else {
  70705. var mat = Bone._tmpMats[0];
  70706. var amat = this.getAbsoluteTransform();
  70707. if (mesh) {
  70708. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70709. }
  70710. else {
  70711. mat.copyFrom(amat);
  70712. }
  70713. mat.m[0] *= this._scalingDeterminant;
  70714. mat.m[1] *= this._scalingDeterminant;
  70715. mat.m[2] *= this._scalingDeterminant;
  70716. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70717. }
  70718. };
  70719. /**
  70720. * Get the rotation matrix of the bone in local or world space.
  70721. * @param space The space that the rotation should be in.
  70722. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70723. * @returns The rotation matrix
  70724. */
  70725. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70726. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70727. var result = BABYLON.Matrix.Identity();
  70728. this.getRotationMatrixToRef(space, mesh, result);
  70729. return result;
  70730. };
  70731. /**
  70732. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70733. * @param space The space that the rotation should be in.
  70734. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70735. * @param result The quaternion that the rotation should be copied to.
  70736. */
  70737. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70739. if (space == BABYLON.Space.LOCAL) {
  70740. this.getLocalMatrix().getRotationMatrixToRef(result);
  70741. }
  70742. else {
  70743. var mat = Bone._tmpMats[0];
  70744. var amat = this.getAbsoluteTransform();
  70745. if (mesh) {
  70746. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70747. }
  70748. else {
  70749. mat.copyFrom(amat);
  70750. }
  70751. mat.m[0] *= this._scalingDeterminant;
  70752. mat.m[1] *= this._scalingDeterminant;
  70753. mat.m[2] *= this._scalingDeterminant;
  70754. mat.getRotationMatrixToRef(result);
  70755. }
  70756. };
  70757. /**
  70758. * Get the world position of a point that is in the local space of the bone.
  70759. * @param position The local position
  70760. * @param mesh The mesh that this bone is attached to.
  70761. * @returns The world position
  70762. */
  70763. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70764. if (mesh === void 0) { mesh = null; }
  70765. var result = BABYLON.Vector3.Zero();
  70766. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70767. return result;
  70768. };
  70769. /**
  70770. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70771. * @param position The local position
  70772. * @param mesh The mesh that this bone is attached to.
  70773. * @param result The vector3 that the world position should be copied to.
  70774. */
  70775. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70776. if (mesh === void 0) { mesh = null; }
  70777. var wm = null;
  70778. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70779. if (mesh) {
  70780. wm = mesh.getWorldMatrix();
  70781. }
  70782. this._skeleton.computeAbsoluteTransforms();
  70783. var tmat = Bone._tmpMats[0];
  70784. if (mesh && wm) {
  70785. tmat.copyFrom(this.getAbsoluteTransform());
  70786. tmat.multiplyToRef(wm, tmat);
  70787. }
  70788. else {
  70789. tmat = this.getAbsoluteTransform();
  70790. }
  70791. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70792. };
  70793. /**
  70794. * Get the local position of a point that is in world space.
  70795. * @param position The world position
  70796. * @param mesh The mesh that this bone is attached to.
  70797. * @returns The local position
  70798. */
  70799. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70800. if (mesh === void 0) { mesh = null; }
  70801. var result = BABYLON.Vector3.Zero();
  70802. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70803. return result;
  70804. };
  70805. /**
  70806. * Get the local position of a point that is in world space and copy it to the result param.
  70807. * @param position The world position
  70808. * @param mesh The mesh that this bone is attached to.
  70809. * @param result The vector3 that the local position should be copied to.
  70810. */
  70811. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70812. if (mesh === void 0) { mesh = null; }
  70813. var wm = null;
  70814. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70815. if (mesh) {
  70816. wm = mesh.getWorldMatrix();
  70817. }
  70818. this._skeleton.computeAbsoluteTransforms();
  70819. var tmat = Bone._tmpMats[0];
  70820. tmat.copyFrom(this.getAbsoluteTransform());
  70821. if (mesh && wm) {
  70822. tmat.multiplyToRef(wm, tmat);
  70823. }
  70824. tmat.invert();
  70825. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70826. };
  70827. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70828. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70829. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70830. return Bone;
  70831. }(BABYLON.Node));
  70832. BABYLON.Bone = Bone;
  70833. })(BABYLON || (BABYLON = {}));
  70834. //# sourceMappingURL=babylon.bone.js.map
  70835. var BABYLON;
  70836. (function (BABYLON) {
  70837. var BoneIKController = /** @class */ (function () {
  70838. function BoneIKController(mesh, bone, options) {
  70839. this.targetPosition = BABYLON.Vector3.Zero();
  70840. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70841. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70842. this.poleAngle = 0;
  70843. this.slerpAmount = 1;
  70844. this._bone1Quat = BABYLON.Quaternion.Identity();
  70845. this._bone1Mat = BABYLON.Matrix.Identity();
  70846. this._bone2Ang = Math.PI;
  70847. this._maxAngle = Math.PI;
  70848. this._rightHandedSystem = false;
  70849. this._bendAxis = BABYLON.Vector3.Right();
  70850. this._slerping = false;
  70851. this._adjustRoll = 0;
  70852. this._bone2 = bone;
  70853. this._bone1 = bone.getParent();
  70854. if (!this._bone1) {
  70855. return;
  70856. }
  70857. this.mesh = mesh;
  70858. var bonePos = bone.getPosition();
  70859. if (bone.getAbsoluteTransform().determinant() > 0) {
  70860. this._rightHandedSystem = true;
  70861. this._bendAxis.x = 0;
  70862. this._bendAxis.y = 0;
  70863. this._bendAxis.z = -1;
  70864. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70865. this._adjustRoll = Math.PI * .5;
  70866. this._bendAxis.z = 1;
  70867. }
  70868. }
  70869. if (this._bone1.length) {
  70870. var boneScale1 = this._bone1.getScale();
  70871. var boneScale2 = this._bone2.getScale();
  70872. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70873. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70874. }
  70875. else if (this._bone1.children[0]) {
  70876. mesh.computeWorldMatrix(true);
  70877. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70878. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70879. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70880. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70881. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70882. }
  70883. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70884. this.maxAngle = Math.PI;
  70885. if (options) {
  70886. if (options.targetMesh) {
  70887. this.targetMesh = options.targetMesh;
  70888. this.targetMesh.computeWorldMatrix(true);
  70889. }
  70890. if (options.poleTargetMesh) {
  70891. this.poleTargetMesh = options.poleTargetMesh;
  70892. this.poleTargetMesh.computeWorldMatrix(true);
  70893. }
  70894. else if (options.poleTargetBone) {
  70895. this.poleTargetBone = options.poleTargetBone;
  70896. }
  70897. else if (this._bone1.getParent()) {
  70898. this.poleTargetBone = this._bone1.getParent();
  70899. }
  70900. if (options.poleTargetLocalOffset) {
  70901. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70902. }
  70903. if (options.poleAngle) {
  70904. this.poleAngle = options.poleAngle;
  70905. }
  70906. if (options.bendAxis) {
  70907. this._bendAxis.copyFrom(options.bendAxis);
  70908. }
  70909. if (options.maxAngle) {
  70910. this.maxAngle = options.maxAngle;
  70911. }
  70912. if (options.slerpAmount) {
  70913. this.slerpAmount = options.slerpAmount;
  70914. }
  70915. }
  70916. }
  70917. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70918. get: function () {
  70919. return this._maxAngle;
  70920. },
  70921. set: function (value) {
  70922. this._setMaxAngle(value);
  70923. },
  70924. enumerable: true,
  70925. configurable: true
  70926. });
  70927. BoneIKController.prototype._setMaxAngle = function (ang) {
  70928. if (ang < 0) {
  70929. ang = 0;
  70930. }
  70931. if (ang > Math.PI || ang == undefined) {
  70932. ang = Math.PI;
  70933. }
  70934. this._maxAngle = ang;
  70935. var a = this._bone1Length;
  70936. var b = this._bone2Length;
  70937. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70938. };
  70939. BoneIKController.prototype.update = function () {
  70940. var bone1 = this._bone1;
  70941. if (!bone1) {
  70942. return;
  70943. }
  70944. var target = this.targetPosition;
  70945. var poleTarget = this.poleTargetPosition;
  70946. var mat1 = BoneIKController._tmpMats[0];
  70947. var mat2 = BoneIKController._tmpMats[1];
  70948. if (this.targetMesh) {
  70949. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70950. }
  70951. if (this.poleTargetBone) {
  70952. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70953. }
  70954. else if (this.poleTargetMesh) {
  70955. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70956. }
  70957. var bonePos = BoneIKController._tmpVecs[0];
  70958. var zaxis = BoneIKController._tmpVecs[1];
  70959. var xaxis = BoneIKController._tmpVecs[2];
  70960. var yaxis = BoneIKController._tmpVecs[3];
  70961. var upAxis = BoneIKController._tmpVecs[4];
  70962. var _tmpQuat = BoneIKController._tmpQuat;
  70963. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70964. poleTarget.subtractToRef(bonePos, upAxis);
  70965. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70966. upAxis.y = 1;
  70967. }
  70968. else {
  70969. upAxis.normalize();
  70970. }
  70971. target.subtractToRef(bonePos, yaxis);
  70972. yaxis.normalize();
  70973. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70974. zaxis.normalize();
  70975. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70976. xaxis.normalize();
  70977. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70978. var a = this._bone1Length;
  70979. var b = this._bone2Length;
  70980. var c = BABYLON.Vector3.Distance(bonePos, target);
  70981. if (this._maxReach > 0) {
  70982. c = Math.min(this._maxReach, c);
  70983. }
  70984. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70985. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70986. if (acosa > 1) {
  70987. acosa = 1;
  70988. }
  70989. if (acosb > 1) {
  70990. acosb = 1;
  70991. }
  70992. if (acosa < -1) {
  70993. acosa = -1;
  70994. }
  70995. if (acosb < -1) {
  70996. acosb = -1;
  70997. }
  70998. var angA = Math.acos(acosa);
  70999. var angB = Math.acos(acosb);
  71000. var angC = -angA - angB;
  71001. if (this._rightHandedSystem) {
  71002. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71003. mat2.multiplyToRef(mat1, mat1);
  71004. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71005. mat2.multiplyToRef(mat1, mat1);
  71006. }
  71007. else {
  71008. var _tmpVec = BoneIKController._tmpVecs[5];
  71009. _tmpVec.copyFrom(this._bendAxis);
  71010. _tmpVec.x *= -1;
  71011. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71012. mat2.multiplyToRef(mat1, mat1);
  71013. }
  71014. if (this.poleAngle) {
  71015. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71016. mat1.multiplyToRef(mat2, mat1);
  71017. }
  71018. if (this._bone1) {
  71019. if (this.slerpAmount < 1) {
  71020. if (!this._slerping) {
  71021. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71022. }
  71023. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71024. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71025. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71026. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71027. this._slerping = true;
  71028. }
  71029. else {
  71030. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71031. this._bone1Mat.copyFrom(mat1);
  71032. this._slerping = false;
  71033. }
  71034. }
  71035. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71036. this._bone2Ang = angC;
  71037. };
  71038. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71039. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71040. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71041. return BoneIKController;
  71042. }());
  71043. BABYLON.BoneIKController = BoneIKController;
  71044. })(BABYLON || (BABYLON = {}));
  71045. //# sourceMappingURL=babylon.boneIKController.js.map
  71046. var BABYLON;
  71047. (function (BABYLON) {
  71048. var BoneLookController = /** @class */ (function () {
  71049. /**
  71050. * Create a BoneLookController
  71051. * @param mesh the mesh that the bone belongs to
  71052. * @param bone the bone that will be looking to the target
  71053. * @param target the target Vector3 to look at
  71054. * @param settings optional settings:
  71055. * - maxYaw: the maximum angle the bone will yaw to
  71056. * - minYaw: the minimum angle the bone will yaw to
  71057. * - maxPitch: the maximum angle the bone will pitch to
  71058. * - minPitch: the minimum angle the bone will yaw to
  71059. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71060. * - upAxis: the up axis of the coordinate system
  71061. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71062. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71063. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71064. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71065. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71066. * - adjustRoll: used to make an adjustment to the roll of the bone
  71067. **/
  71068. function BoneLookController(mesh, bone, target, options) {
  71069. /**
  71070. * The up axis of the coordinate system that is used when the bone is rotated.
  71071. */
  71072. this.upAxis = BABYLON.Vector3.Up();
  71073. /**
  71074. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71075. */
  71076. this.upAxisSpace = BABYLON.Space.LOCAL;
  71077. /**
  71078. * Used to make an adjustment to the yaw of the bone.
  71079. */
  71080. this.adjustYaw = 0;
  71081. /**
  71082. * Used to make an adjustment to the pitch of the bone.
  71083. */
  71084. this.adjustPitch = 0;
  71085. /**
  71086. * Used to make an adjustment to the roll of the bone.
  71087. */
  71088. this.adjustRoll = 0;
  71089. /**
  71090. * 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).
  71091. */
  71092. this.slerpAmount = 1;
  71093. this._boneQuat = BABYLON.Quaternion.Identity();
  71094. this._slerping = false;
  71095. this._firstFrameSkipped = false;
  71096. this._fowardAxis = BABYLON.Vector3.Forward();
  71097. this.mesh = mesh;
  71098. this.bone = bone;
  71099. this.target = target;
  71100. if (options) {
  71101. if (options.adjustYaw) {
  71102. this.adjustYaw = options.adjustYaw;
  71103. }
  71104. if (options.adjustPitch) {
  71105. this.adjustPitch = options.adjustPitch;
  71106. }
  71107. if (options.adjustRoll) {
  71108. this.adjustRoll = options.adjustRoll;
  71109. }
  71110. if (options.maxYaw != null) {
  71111. this.maxYaw = options.maxYaw;
  71112. }
  71113. else {
  71114. this.maxYaw = Math.PI;
  71115. }
  71116. if (options.minYaw != null) {
  71117. this.minYaw = options.minYaw;
  71118. }
  71119. else {
  71120. this.minYaw = -Math.PI;
  71121. }
  71122. if (options.maxPitch != null) {
  71123. this.maxPitch = options.maxPitch;
  71124. }
  71125. else {
  71126. this.maxPitch = Math.PI;
  71127. }
  71128. if (options.minPitch != null) {
  71129. this.minPitch = options.minPitch;
  71130. }
  71131. else {
  71132. this.minPitch = -Math.PI;
  71133. }
  71134. if (options.slerpAmount != null) {
  71135. this.slerpAmount = options.slerpAmount;
  71136. }
  71137. if (options.upAxis != null) {
  71138. this.upAxis = options.upAxis;
  71139. }
  71140. if (options.upAxisSpace != null) {
  71141. this.upAxisSpace = options.upAxisSpace;
  71142. }
  71143. if (options.yawAxis != null || options.pitchAxis != null) {
  71144. var newYawAxis = BABYLON.Axis.Y;
  71145. var newPitchAxis = BABYLON.Axis.X;
  71146. if (options.yawAxis != null) {
  71147. newYawAxis = options.yawAxis.clone();
  71148. newYawAxis.normalize();
  71149. }
  71150. if (options.pitchAxis != null) {
  71151. newPitchAxis = options.pitchAxis.clone();
  71152. newPitchAxis.normalize();
  71153. }
  71154. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71155. this._transformYawPitch = BABYLON.Matrix.Identity();
  71156. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71157. this._transformYawPitchInv = this._transformYawPitch.clone();
  71158. this._transformYawPitch.invert();
  71159. }
  71160. }
  71161. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71162. this.upAxisSpace = BABYLON.Space.LOCAL;
  71163. }
  71164. }
  71165. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71166. /**
  71167. * Get/set the minimum yaw angle that the bone can look to.
  71168. */
  71169. get: function () {
  71170. return this._minYaw;
  71171. },
  71172. set: function (value) {
  71173. this._minYaw = value;
  71174. this._minYawSin = Math.sin(value);
  71175. this._minYawCos = Math.cos(value);
  71176. if (this._maxYaw != null) {
  71177. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71178. this._yawRange = this._maxYaw - this._minYaw;
  71179. }
  71180. },
  71181. enumerable: true,
  71182. configurable: true
  71183. });
  71184. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71185. /**
  71186. * Get/set the maximum yaw angle that the bone can look to.
  71187. */
  71188. get: function () {
  71189. return this._maxYaw;
  71190. },
  71191. set: function (value) {
  71192. this._maxYaw = value;
  71193. this._maxYawSin = Math.sin(value);
  71194. this._maxYawCos = Math.cos(value);
  71195. if (this._minYaw != null) {
  71196. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71197. this._yawRange = this._maxYaw - this._minYaw;
  71198. }
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71204. /**
  71205. * Get/set the minimum pitch angle that the bone can look to.
  71206. */
  71207. get: function () {
  71208. return this._minPitch;
  71209. },
  71210. set: function (value) {
  71211. this._minPitch = value;
  71212. this._minPitchTan = Math.tan(value);
  71213. },
  71214. enumerable: true,
  71215. configurable: true
  71216. });
  71217. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71218. /**
  71219. * Get/set the maximum pitch angle that the bone can look to.
  71220. */
  71221. get: function () {
  71222. return this._maxPitch;
  71223. },
  71224. set: function (value) {
  71225. this._maxPitch = value;
  71226. this._maxPitchTan = Math.tan(value);
  71227. },
  71228. enumerable: true,
  71229. configurable: true
  71230. });
  71231. /**
  71232. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71233. */
  71234. BoneLookController.prototype.update = function () {
  71235. //skip the first frame when slerping so that the mesh rotation is correct
  71236. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71237. this._firstFrameSkipped = true;
  71238. return;
  71239. }
  71240. var bone = this.bone;
  71241. var bonePos = BoneLookController._tmpVecs[0];
  71242. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71243. var target = this.target;
  71244. var _tmpMat1 = BoneLookController._tmpMats[0];
  71245. var _tmpMat2 = BoneLookController._tmpMats[1];
  71246. var mesh = this.mesh;
  71247. var parentBone = bone.getParent();
  71248. var upAxis = BoneLookController._tmpVecs[1];
  71249. upAxis.copyFrom(this.upAxis);
  71250. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71251. if (this._transformYawPitch) {
  71252. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71253. }
  71254. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71255. }
  71256. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71257. mesh.getDirectionToRef(upAxis, upAxis);
  71258. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71259. upAxis.normalize();
  71260. }
  71261. }
  71262. var checkYaw = false;
  71263. var checkPitch = false;
  71264. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71265. checkYaw = true;
  71266. }
  71267. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71268. checkPitch = true;
  71269. }
  71270. if (checkYaw || checkPitch) {
  71271. var spaceMat = BoneLookController._tmpMats[2];
  71272. var spaceMatInv = BoneLookController._tmpMats[3];
  71273. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71274. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71275. }
  71276. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71277. spaceMat.copyFrom(mesh.getWorldMatrix());
  71278. }
  71279. else {
  71280. var forwardAxis = BoneLookController._tmpVecs[2];
  71281. forwardAxis.copyFrom(this._fowardAxis);
  71282. if (this._transformYawPitch) {
  71283. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71284. }
  71285. if (parentBone) {
  71286. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71287. }
  71288. else {
  71289. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71290. }
  71291. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71292. rightAxis.normalize();
  71293. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71294. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71295. }
  71296. spaceMat.invertToRef(spaceMatInv);
  71297. var xzlen = null;
  71298. if (checkPitch) {
  71299. var localTarget = BoneLookController._tmpVecs[3];
  71300. target.subtractToRef(bonePos, localTarget);
  71301. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71302. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71303. var pitch = Math.atan2(localTarget.y, xzlen);
  71304. var newPitch = pitch;
  71305. if (pitch > this._maxPitch) {
  71306. localTarget.y = this._maxPitchTan * xzlen;
  71307. newPitch = this._maxPitch;
  71308. }
  71309. else if (pitch < this._minPitch) {
  71310. localTarget.y = this._minPitchTan * xzlen;
  71311. newPitch = this._minPitch;
  71312. }
  71313. if (pitch != newPitch) {
  71314. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71315. localTarget.addInPlace(bonePos);
  71316. target = localTarget;
  71317. }
  71318. }
  71319. if (checkYaw) {
  71320. var localTarget = BoneLookController._tmpVecs[4];
  71321. target.subtractToRef(bonePos, localTarget);
  71322. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71323. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71324. var newYaw = yaw;
  71325. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71326. if (xzlen == null) {
  71327. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71328. }
  71329. if (this._yawRange > Math.PI) {
  71330. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71331. localTarget.z = this._maxYawCos * xzlen;
  71332. localTarget.x = this._maxYawSin * xzlen;
  71333. newYaw = this._maxYaw;
  71334. }
  71335. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71336. localTarget.z = this._minYawCos * xzlen;
  71337. localTarget.x = this._minYawSin * xzlen;
  71338. newYaw = this._minYaw;
  71339. }
  71340. }
  71341. else {
  71342. if (yaw > this._maxYaw) {
  71343. localTarget.z = this._maxYawCos * xzlen;
  71344. localTarget.x = this._maxYawSin * xzlen;
  71345. newYaw = this._maxYaw;
  71346. }
  71347. else if (yaw < this._minYaw) {
  71348. localTarget.z = this._minYawCos * xzlen;
  71349. localTarget.x = this._minYawSin * xzlen;
  71350. newYaw = this._minYaw;
  71351. }
  71352. }
  71353. }
  71354. if (this._slerping && this._yawRange > Math.PI) {
  71355. //are we going to be crossing into the min/max region?
  71356. var boneFwd = BoneLookController._tmpVecs[8];
  71357. boneFwd.copyFrom(BABYLON.Axis.Z);
  71358. if (this._transformYawPitch) {
  71359. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71360. }
  71361. var boneRotMat = BoneLookController._tmpMats[4];
  71362. this._boneQuat.toRotationMatrix(boneRotMat);
  71363. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71364. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71365. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71366. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71367. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71368. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71369. if (angBtwTar > angBtwMidYaw) {
  71370. if (xzlen == null) {
  71371. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71372. }
  71373. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71374. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71375. if (angBtwMin < angBtwMax) {
  71376. newYaw = boneYaw + Math.PI * .75;
  71377. localTarget.z = Math.cos(newYaw) * xzlen;
  71378. localTarget.x = Math.sin(newYaw) * xzlen;
  71379. }
  71380. else {
  71381. newYaw = boneYaw - Math.PI * .75;
  71382. localTarget.z = Math.cos(newYaw) * xzlen;
  71383. localTarget.x = Math.sin(newYaw) * xzlen;
  71384. }
  71385. }
  71386. }
  71387. if (yaw != newYaw) {
  71388. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71389. localTarget.addInPlace(bonePos);
  71390. target = localTarget;
  71391. }
  71392. }
  71393. }
  71394. var zaxis = BoneLookController._tmpVecs[5];
  71395. var xaxis = BoneLookController._tmpVecs[6];
  71396. var yaxis = BoneLookController._tmpVecs[7];
  71397. var _tmpQuat = BoneLookController._tmpQuat;
  71398. target.subtractToRef(bonePos, zaxis);
  71399. zaxis.normalize();
  71400. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71401. xaxis.normalize();
  71402. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71403. yaxis.normalize();
  71404. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71405. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71406. return;
  71407. }
  71408. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71409. return;
  71410. }
  71411. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71412. return;
  71413. }
  71414. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71415. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71416. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71417. }
  71418. if (this.slerpAmount < 1) {
  71419. if (!this._slerping) {
  71420. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71421. }
  71422. if (this._transformYawPitch) {
  71423. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71424. }
  71425. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71426. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71427. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71428. this._slerping = true;
  71429. }
  71430. else {
  71431. if (this._transformYawPitch) {
  71432. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71433. }
  71434. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71435. this._slerping = false;
  71436. }
  71437. };
  71438. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71439. var angDiff = ang2 - ang1;
  71440. angDiff %= Math.PI * 2;
  71441. if (angDiff > Math.PI) {
  71442. angDiff -= Math.PI * 2;
  71443. }
  71444. else if (angDiff < -Math.PI) {
  71445. angDiff += Math.PI * 2;
  71446. }
  71447. return angDiff;
  71448. };
  71449. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71450. ang1 %= (2 * Math.PI);
  71451. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71452. ang2 %= (2 * Math.PI);
  71453. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71454. var ab = 0;
  71455. if (ang1 < ang2) {
  71456. ab = ang2 - ang1;
  71457. }
  71458. else {
  71459. ab = ang1 - ang2;
  71460. }
  71461. if (ab > Math.PI) {
  71462. ab = Math.PI * 2 - ab;
  71463. }
  71464. return ab;
  71465. };
  71466. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71467. ang %= (2 * Math.PI);
  71468. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71469. ang1 %= (2 * Math.PI);
  71470. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71471. ang2 %= (2 * Math.PI);
  71472. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71473. if (ang1 < ang2) {
  71474. if (ang > ang1 && ang < ang2) {
  71475. return true;
  71476. }
  71477. }
  71478. else {
  71479. if (ang > ang2 && ang < ang1) {
  71480. return true;
  71481. }
  71482. }
  71483. return false;
  71484. };
  71485. 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()];
  71486. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71487. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71488. return BoneLookController;
  71489. }());
  71490. BABYLON.BoneLookController = BoneLookController;
  71491. })(BABYLON || (BABYLON = {}));
  71492. //# sourceMappingURL=babylon.boneLookController.js.map
  71493. var BABYLON;
  71494. (function (BABYLON) {
  71495. var Skeleton = /** @class */ (function () {
  71496. function Skeleton(name, id, scene) {
  71497. this.name = name;
  71498. this.id = id;
  71499. this.bones = new Array();
  71500. this.needInitialSkinMatrix = false;
  71501. this._isDirty = true;
  71502. this._meshesWithPoseMatrix = new Array();
  71503. this._identity = BABYLON.Matrix.Identity();
  71504. this._ranges = {};
  71505. this._lastAbsoluteTransformsUpdateId = -1;
  71506. /**
  71507. * Specifies if the skeleton should be serialized.
  71508. */
  71509. this.doNotSerialize = false;
  71510. // Events
  71511. /**
  71512. * An event triggered before computing the skeleton's matrices
  71513. * @type {BABYLON.Observable}
  71514. */
  71515. this.onBeforeComputeObservable = new BABYLON.Observable();
  71516. this.bones = [];
  71517. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71518. scene.skeletons.push(this);
  71519. //make sure it will recalculate the matrix next time prepare is called.
  71520. this._isDirty = true;
  71521. }
  71522. // Members
  71523. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71524. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71525. return mesh._bonesTransformMatrices;
  71526. }
  71527. if (!this._transformMatrices) {
  71528. this.prepare();
  71529. }
  71530. return this._transformMatrices;
  71531. };
  71532. Skeleton.prototype.getScene = function () {
  71533. return this._scene;
  71534. };
  71535. // Methods
  71536. /**
  71537. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71538. */
  71539. Skeleton.prototype.toString = function (fullDetails) {
  71540. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71541. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71542. if (fullDetails) {
  71543. ret += ", Ranges: {";
  71544. var first = true;
  71545. for (var name_1 in this._ranges) {
  71546. if (first) {
  71547. ret += ", ";
  71548. first = false;
  71549. }
  71550. ret += name_1;
  71551. }
  71552. ret += "}";
  71553. }
  71554. return ret;
  71555. };
  71556. /**
  71557. * Get bone's index searching by name
  71558. * @param {string} name is bone's name to search for
  71559. * @return {number} Indice of the bone. Returns -1 if not found
  71560. */
  71561. Skeleton.prototype.getBoneIndexByName = function (name) {
  71562. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71563. if (this.bones[boneIndex].name === name) {
  71564. return boneIndex;
  71565. }
  71566. }
  71567. return -1;
  71568. };
  71569. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71570. // check name not already in use
  71571. if (!this._ranges[name]) {
  71572. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71573. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71574. if (this.bones[i].animations[0]) {
  71575. this.bones[i].animations[0].createRange(name, from, to);
  71576. }
  71577. }
  71578. }
  71579. };
  71580. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71581. if (deleteFrames === void 0) { deleteFrames = true; }
  71582. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71583. if (this.bones[i].animations[0]) {
  71584. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71585. }
  71586. }
  71587. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71588. };
  71589. Skeleton.prototype.getAnimationRange = function (name) {
  71590. return this._ranges[name];
  71591. };
  71592. /**
  71593. * Returns as an Array, all AnimationRanges defined on this skeleton
  71594. */
  71595. Skeleton.prototype.getAnimationRanges = function () {
  71596. var animationRanges = [];
  71597. var name;
  71598. var i = 0;
  71599. for (name in this._ranges) {
  71600. animationRanges[i] = this._ranges[name];
  71601. i++;
  71602. }
  71603. return animationRanges;
  71604. };
  71605. /**
  71606. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71607. */
  71608. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71609. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71610. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71611. return false;
  71612. }
  71613. var ret = true;
  71614. var frameOffset = this._getHighestAnimationFrame() + 1;
  71615. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71616. var boneDict = {};
  71617. var sourceBones = source.bones;
  71618. var nBones;
  71619. var i;
  71620. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71621. boneDict[sourceBones[i].name] = sourceBones[i];
  71622. }
  71623. if (this.bones.length !== sourceBones.length) {
  71624. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71625. ret = false;
  71626. }
  71627. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71628. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71629. var boneName = this.bones[i].name;
  71630. var sourceBone = boneDict[boneName];
  71631. if (sourceBone) {
  71632. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71633. }
  71634. else {
  71635. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71636. ret = false;
  71637. }
  71638. }
  71639. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71640. var range = source.getAnimationRange(name);
  71641. if (range) {
  71642. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71643. }
  71644. return ret;
  71645. };
  71646. Skeleton.prototype.returnToRest = function () {
  71647. for (var index = 0; index < this.bones.length; index++) {
  71648. this.bones[index].returnToRest();
  71649. }
  71650. };
  71651. Skeleton.prototype._getHighestAnimationFrame = function () {
  71652. var ret = 0;
  71653. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71654. if (this.bones[i].animations[0]) {
  71655. var highest = this.bones[i].animations[0].getHighestFrame();
  71656. if (ret < highest) {
  71657. ret = highest;
  71658. }
  71659. }
  71660. }
  71661. return ret;
  71662. };
  71663. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71664. var range = this.getAnimationRange(name);
  71665. if (!range) {
  71666. return null;
  71667. }
  71668. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71669. };
  71670. Skeleton.prototype._markAsDirty = function () {
  71671. this._isDirty = true;
  71672. };
  71673. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71674. this._meshesWithPoseMatrix.push(mesh);
  71675. };
  71676. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71677. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71678. if (index > -1) {
  71679. this._meshesWithPoseMatrix.splice(index, 1);
  71680. }
  71681. };
  71682. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71683. this.onBeforeComputeObservable.notifyObservers(this);
  71684. for (var index = 0; index < this.bones.length; index++) {
  71685. var bone = this.bones[index];
  71686. var parentBone = bone.getParent();
  71687. if (parentBone) {
  71688. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71689. }
  71690. else {
  71691. if (initialSkinMatrix) {
  71692. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71693. }
  71694. else {
  71695. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71696. }
  71697. }
  71698. if (bone._index !== -1) {
  71699. var mappedIndex = bone._index === null ? index : bone._index;
  71700. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71701. }
  71702. }
  71703. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71704. };
  71705. Skeleton.prototype.prepare = function () {
  71706. if (!this._isDirty) {
  71707. return;
  71708. }
  71709. if (this.needInitialSkinMatrix) {
  71710. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71711. var mesh = this._meshesWithPoseMatrix[index];
  71712. var poseMatrix = mesh.getPoseMatrix();
  71713. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71714. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71715. }
  71716. if (this._synchronizedWithMesh !== mesh) {
  71717. this._synchronizedWithMesh = mesh;
  71718. // Prepare bones
  71719. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71720. var bone = this.bones[boneIndex];
  71721. if (!bone.getParent()) {
  71722. var matrix = bone.getBaseMatrix();
  71723. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71724. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71725. }
  71726. }
  71727. }
  71728. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71729. }
  71730. }
  71731. else {
  71732. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71733. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71734. }
  71735. this._computeTransformMatrices(this._transformMatrices, null);
  71736. }
  71737. this._isDirty = false;
  71738. this._scene._activeBones.addCount(this.bones.length, false);
  71739. };
  71740. Skeleton.prototype.getAnimatables = function () {
  71741. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71742. this._animatables = [];
  71743. for (var index = 0; index < this.bones.length; index++) {
  71744. this._animatables.push(this.bones[index]);
  71745. }
  71746. }
  71747. return this._animatables;
  71748. };
  71749. Skeleton.prototype.clone = function (name, id) {
  71750. var result = new Skeleton(name, id || name, this._scene);
  71751. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71752. for (var index = 0; index < this.bones.length; index++) {
  71753. var source = this.bones[index];
  71754. var parentBone = null;
  71755. var parent_1 = source.getParent();
  71756. if (parent_1) {
  71757. var parentIndex = this.bones.indexOf(parent_1);
  71758. parentBone = result.bones[parentIndex];
  71759. }
  71760. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71761. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71762. }
  71763. if (this._ranges) {
  71764. result._ranges = {};
  71765. for (var rangeName in this._ranges) {
  71766. var range = this._ranges[rangeName];
  71767. if (range) {
  71768. result._ranges[rangeName] = range.clone();
  71769. }
  71770. }
  71771. }
  71772. this._isDirty = true;
  71773. return result;
  71774. };
  71775. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71776. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71777. this.bones.forEach(function (bone) {
  71778. bone.animations.forEach(function (animation) {
  71779. animation.enableBlending = true;
  71780. animation.blendingSpeed = blendingSpeed;
  71781. });
  71782. });
  71783. };
  71784. Skeleton.prototype.dispose = function () {
  71785. this._meshesWithPoseMatrix = [];
  71786. // Animations
  71787. this.getScene().stopAnimation(this);
  71788. // Remove from scene
  71789. this.getScene().removeSkeleton(this);
  71790. };
  71791. Skeleton.prototype.serialize = function () {
  71792. var serializationObject = {};
  71793. serializationObject.name = this.name;
  71794. serializationObject.id = this.id;
  71795. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71796. serializationObject.bones = [];
  71797. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71798. for (var index = 0; index < this.bones.length; index++) {
  71799. var bone = this.bones[index];
  71800. var parent_2 = bone.getParent();
  71801. var serializedBone = {
  71802. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71803. name: bone.name,
  71804. matrix: bone.getBaseMatrix().toArray(),
  71805. rest: bone.getRestPose().toArray()
  71806. };
  71807. serializationObject.bones.push(serializedBone);
  71808. if (bone.length) {
  71809. serializedBone.length = bone.length;
  71810. }
  71811. if (bone.animations && bone.animations.length > 0) {
  71812. serializedBone.animation = bone.animations[0].serialize();
  71813. }
  71814. serializationObject.ranges = [];
  71815. for (var name in this._ranges) {
  71816. var source = this._ranges[name];
  71817. if (!source) {
  71818. continue;
  71819. }
  71820. var range = {};
  71821. range.name = name;
  71822. range.from = source.from;
  71823. range.to = source.to;
  71824. serializationObject.ranges.push(range);
  71825. }
  71826. }
  71827. return serializationObject;
  71828. };
  71829. Skeleton.Parse = function (parsedSkeleton, scene) {
  71830. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71831. if (parsedSkeleton.dimensionsAtRest) {
  71832. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71833. }
  71834. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71835. var index;
  71836. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71837. var parsedBone = parsedSkeleton.bones[index];
  71838. var parentBone = null;
  71839. if (parsedBone.parentBoneIndex > -1) {
  71840. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71841. }
  71842. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71843. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71844. if (parsedBone.length) {
  71845. bone.length = parsedBone.length;
  71846. }
  71847. if (parsedBone.animation) {
  71848. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71849. }
  71850. }
  71851. // placed after bones, so createAnimationRange can cascade down
  71852. if (parsedSkeleton.ranges) {
  71853. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71854. var data = parsedSkeleton.ranges[index];
  71855. skeleton.createAnimationRange(data.name, data.from, data.to);
  71856. }
  71857. }
  71858. return skeleton;
  71859. };
  71860. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71861. if (forceUpdate === void 0) { forceUpdate = false; }
  71862. var renderId = this._scene.getRenderId();
  71863. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71864. this.bones[0].computeAbsoluteTransforms();
  71865. this._lastAbsoluteTransformsUpdateId = renderId;
  71866. }
  71867. };
  71868. Skeleton.prototype.getPoseMatrix = function () {
  71869. var poseMatrix = null;
  71870. if (this._meshesWithPoseMatrix.length > 0) {
  71871. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71872. }
  71873. return poseMatrix;
  71874. };
  71875. Skeleton.prototype.sortBones = function () {
  71876. var bones = new Array();
  71877. var visited = new Array(this.bones.length);
  71878. for (var index = 0; index < this.bones.length; index++) {
  71879. this._sortBones(index, bones, visited);
  71880. }
  71881. this.bones = bones;
  71882. };
  71883. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71884. if (visited[index]) {
  71885. return;
  71886. }
  71887. visited[index] = true;
  71888. var bone = this.bones[index];
  71889. if (bone._index === undefined) {
  71890. bone._index = index;
  71891. }
  71892. var parentBone = bone.getParent();
  71893. if (parentBone) {
  71894. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71895. }
  71896. bones.push(bone);
  71897. };
  71898. return Skeleton;
  71899. }());
  71900. BABYLON.Skeleton = Skeleton;
  71901. })(BABYLON || (BABYLON = {}));
  71902. //# sourceMappingURL=babylon.skeleton.js.map
  71903. var BABYLON;
  71904. (function (BABYLON) {
  71905. var SphericalPolynomial = /** @class */ (function () {
  71906. function SphericalPolynomial() {
  71907. this.x = BABYLON.Vector3.Zero();
  71908. this.y = BABYLON.Vector3.Zero();
  71909. this.z = BABYLON.Vector3.Zero();
  71910. this.xx = BABYLON.Vector3.Zero();
  71911. this.yy = BABYLON.Vector3.Zero();
  71912. this.zz = BABYLON.Vector3.Zero();
  71913. this.xy = BABYLON.Vector3.Zero();
  71914. this.yz = BABYLON.Vector3.Zero();
  71915. this.zx = BABYLON.Vector3.Zero();
  71916. }
  71917. SphericalPolynomial.prototype.addAmbient = function (color) {
  71918. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71919. this.xx = this.xx.add(colorVector);
  71920. this.yy = this.yy.add(colorVector);
  71921. this.zz = this.zz.add(colorVector);
  71922. };
  71923. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71924. var result = new SphericalPolynomial();
  71925. result.x = harmonics.L11.scale(1.02333);
  71926. result.y = harmonics.L1_1.scale(1.02333);
  71927. result.z = harmonics.L10.scale(1.02333);
  71928. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71929. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71930. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71931. result.yz = harmonics.L2_1.scale(0.858086);
  71932. result.zx = harmonics.L21.scale(0.858086);
  71933. result.xy = harmonics.L2_2.scale(0.858086);
  71934. result.scale(1.0 / Math.PI);
  71935. return result;
  71936. };
  71937. SphericalPolynomial.prototype.scale = function (scale) {
  71938. this.x = this.x.scale(scale);
  71939. this.y = this.y.scale(scale);
  71940. this.z = this.z.scale(scale);
  71941. this.xx = this.xx.scale(scale);
  71942. this.yy = this.yy.scale(scale);
  71943. this.zz = this.zz.scale(scale);
  71944. this.yz = this.yz.scale(scale);
  71945. this.zx = this.zx.scale(scale);
  71946. this.xy = this.xy.scale(scale);
  71947. };
  71948. return SphericalPolynomial;
  71949. }());
  71950. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71951. var SphericalHarmonics = /** @class */ (function () {
  71952. function SphericalHarmonics() {
  71953. this.L00 = BABYLON.Vector3.Zero();
  71954. this.L1_1 = BABYLON.Vector3.Zero();
  71955. this.L10 = BABYLON.Vector3.Zero();
  71956. this.L11 = BABYLON.Vector3.Zero();
  71957. this.L2_2 = BABYLON.Vector3.Zero();
  71958. this.L2_1 = BABYLON.Vector3.Zero();
  71959. this.L20 = BABYLON.Vector3.Zero();
  71960. this.L21 = BABYLON.Vector3.Zero();
  71961. this.L22 = BABYLON.Vector3.Zero();
  71962. }
  71963. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71964. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71965. var c = colorVector.scale(deltaSolidAngle);
  71966. this.L00 = this.L00.add(c.scale(0.282095));
  71967. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71968. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71969. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71970. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71971. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71972. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71973. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71974. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71975. };
  71976. SphericalHarmonics.prototype.scale = function (scale) {
  71977. this.L00 = this.L00.scale(scale);
  71978. this.L1_1 = this.L1_1.scale(scale);
  71979. this.L10 = this.L10.scale(scale);
  71980. this.L11 = this.L11.scale(scale);
  71981. this.L2_2 = this.L2_2.scale(scale);
  71982. this.L2_1 = this.L2_1.scale(scale);
  71983. this.L20 = this.L20.scale(scale);
  71984. this.L21 = this.L21.scale(scale);
  71985. this.L22 = this.L22.scale(scale);
  71986. };
  71987. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71988. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71989. //
  71990. // E_lm = A_l * L_lm
  71991. //
  71992. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71993. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71994. // the scaling factors are given in equation 9.
  71995. // Constant (Band 0)
  71996. this.L00 = this.L00.scale(3.141593);
  71997. // Linear (Band 1)
  71998. this.L1_1 = this.L1_1.scale(2.094395);
  71999. this.L10 = this.L10.scale(2.094395);
  72000. this.L11 = this.L11.scale(2.094395);
  72001. // Quadratic (Band 2)
  72002. this.L2_2 = this.L2_2.scale(0.785398);
  72003. this.L2_1 = this.L2_1.scale(0.785398);
  72004. this.L20 = this.L20.scale(0.785398);
  72005. this.L21 = this.L21.scale(0.785398);
  72006. this.L22 = this.L22.scale(0.785398);
  72007. };
  72008. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72009. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72010. // L = (1/pi) * E * rho
  72011. //
  72012. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72013. this.scale(1.0 / Math.PI);
  72014. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72015. // (The pixel shader must apply albedo after texture fetches, etc).
  72016. };
  72017. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72018. var result = new SphericalHarmonics();
  72019. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72020. result.L1_1 = polynomial.y.scale(0.977204);
  72021. result.L10 = polynomial.z.scale(0.977204);
  72022. result.L11 = polynomial.x.scale(0.977204);
  72023. result.L2_2 = polynomial.xy.scale(1.16538);
  72024. result.L2_1 = polynomial.yz.scale(1.16538);
  72025. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72026. result.L21 = polynomial.zx.scale(1.16538);
  72027. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72028. result.scale(Math.PI);
  72029. return result;
  72030. };
  72031. return SphericalHarmonics;
  72032. }());
  72033. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72034. })(BABYLON || (BABYLON = {}));
  72035. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72036. var BABYLON;
  72037. (function (BABYLON) {
  72038. var FileFaceOrientation = /** @class */ (function () {
  72039. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72040. this.name = name;
  72041. this.worldAxisForNormal = worldAxisForNormal;
  72042. this.worldAxisForFileX = worldAxisForFileX;
  72043. this.worldAxisForFileY = worldAxisForFileY;
  72044. }
  72045. return FileFaceOrientation;
  72046. }());
  72047. ;
  72048. /**
  72049. * Helper class dealing with the extraction of spherical polynomial dataArray
  72050. * from a cube map.
  72051. */
  72052. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72053. function CubeMapToSphericalPolynomialTools() {
  72054. }
  72055. /**
  72056. * Converts a texture to the according Spherical Polynomial data.
  72057. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72058. *
  72059. * @param texture The texture to extract the information from.
  72060. * @return The Spherical Polynomial data.
  72061. */
  72062. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72063. if (!texture.isCube) {
  72064. // Only supports cube Textures currently.
  72065. return null;
  72066. }
  72067. var size = texture.getSize().width;
  72068. var right = texture.readPixels(0);
  72069. var left = texture.readPixels(1);
  72070. var up;
  72071. var down;
  72072. if (texture.isRenderTarget) {
  72073. up = texture.readPixels(3);
  72074. down = texture.readPixels(2);
  72075. }
  72076. else {
  72077. up = texture.readPixels(2);
  72078. down = texture.readPixels(3);
  72079. }
  72080. var front = texture.readPixels(4);
  72081. var back = texture.readPixels(5);
  72082. var gammaSpace = texture.gammaSpace;
  72083. // Always read as RGBA.
  72084. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72085. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72086. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72087. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72088. }
  72089. var cubeInfo = {
  72090. size: size,
  72091. right: right,
  72092. left: left,
  72093. up: up,
  72094. down: down,
  72095. front: front,
  72096. back: back,
  72097. format: format,
  72098. type: type,
  72099. gammaSpace: gammaSpace,
  72100. };
  72101. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72102. };
  72103. /**
  72104. * Converts a cubemap to the according Spherical Polynomial data.
  72105. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72106. *
  72107. * @param cubeInfo The Cube map to extract the information from.
  72108. * @return The Spherical Polynomial data.
  72109. */
  72110. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72111. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72112. var totalSolidAngle = 0.0;
  72113. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72114. var du = 2.0 / cubeInfo.size;
  72115. var dv = du;
  72116. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72117. var minUV = du * 0.5 - 1.0;
  72118. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72119. var fileFace = this.FileFaces[faceIndex];
  72120. var dataArray = cubeInfo[fileFace.name];
  72121. var v = minUV;
  72122. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72123. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72124. // Because SP is still linear, so summation is fine in that basis.
  72125. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72126. for (var y = 0; y < cubeInfo.size; y++) {
  72127. var u = minUV;
  72128. for (var x = 0; x < cubeInfo.size; x++) {
  72129. // World direction (not normalised)
  72130. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72131. worldDirection.normalize();
  72132. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72133. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72134. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72135. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72136. // Handle Integer types.
  72137. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72138. r /= 255;
  72139. g /= 255;
  72140. b /= 255;
  72141. }
  72142. // Handle Gamma space textures.
  72143. if (cubeInfo.gammaSpace) {
  72144. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72145. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72146. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72147. }
  72148. var color = new BABYLON.Color3(r, g, b);
  72149. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72150. totalSolidAngle += deltaSolidAngle;
  72151. u += du;
  72152. }
  72153. v += dv;
  72154. }
  72155. }
  72156. // Solid angle for entire sphere is 4*pi
  72157. var sphereSolidAngle = 4.0 * Math.PI;
  72158. // Adjust the solid angle to allow for how many faces we processed.
  72159. var facesProcessed = 6.0;
  72160. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72161. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72162. // This is needed because the numerical integration over the cube uses a
  72163. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72164. // and also to compensate for accumulative error due to float precision in the summation.
  72165. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72166. sphericalHarmonics.scale(correctionFactor);
  72167. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72168. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72169. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72170. };
  72171. CubeMapToSphericalPolynomialTools.FileFaces = [
  72172. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72173. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72174. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72175. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72176. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72177. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72178. ];
  72179. return CubeMapToSphericalPolynomialTools;
  72180. }());
  72181. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72182. })(BABYLON || (BABYLON = {}));
  72183. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72184. var BABYLON;
  72185. (function (BABYLON) {
  72186. /**
  72187. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72188. */
  72189. var PanoramaToCubeMapTools = /** @class */ (function () {
  72190. function PanoramaToCubeMapTools() {
  72191. }
  72192. /**
  72193. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72194. *
  72195. * @param float32Array The source data.
  72196. * @param inputWidth The width of the input panorama.
  72197. * @param inputhHeight The height of the input panorama.
  72198. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72199. * @return The cubemap data
  72200. */
  72201. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72202. if (!float32Array) {
  72203. throw "ConvertPanoramaToCubemap: input cannot be null";
  72204. }
  72205. if (float32Array.length != inputWidth * inputHeight * 3) {
  72206. throw "ConvertPanoramaToCubemap: input size is wrong";
  72207. }
  72208. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72209. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72210. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72211. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72212. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72213. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72214. return {
  72215. front: textureFront,
  72216. back: textureBack,
  72217. left: textureLeft,
  72218. right: textureRight,
  72219. up: textureUp,
  72220. down: textureDown,
  72221. size: size,
  72222. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72223. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72224. gammaSpace: false,
  72225. };
  72226. };
  72227. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72228. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72229. var textureArray = new Float32Array(buffer);
  72230. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72231. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72232. var dy = 1 / texSize;
  72233. var fy = 0;
  72234. for (var y = 0; y < texSize; y++) {
  72235. var xv1 = faceData[0];
  72236. var xv2 = faceData[2];
  72237. for (var x = 0; x < texSize; x++) {
  72238. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72239. v.normalize();
  72240. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72241. // 3 channels per pixels
  72242. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72243. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72244. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72245. xv1 = xv1.add(rotDX1);
  72246. xv2 = xv2.add(rotDX2);
  72247. }
  72248. fy += dy;
  72249. }
  72250. return textureArray;
  72251. };
  72252. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72253. var theta = Math.atan2(vDir.z, vDir.x);
  72254. var phi = Math.acos(vDir.y);
  72255. while (theta < -Math.PI)
  72256. theta += 2 * Math.PI;
  72257. while (theta > Math.PI)
  72258. theta -= 2 * Math.PI;
  72259. var dx = theta / Math.PI;
  72260. var dy = phi / Math.PI;
  72261. // recenter.
  72262. dx = dx * 0.5 + 0.5;
  72263. var px = Math.round(dx * inputWidth);
  72264. if (px < 0)
  72265. px = 0;
  72266. else if (px >= inputWidth)
  72267. px = inputWidth - 1;
  72268. var py = Math.round(dy * inputHeight);
  72269. if (py < 0)
  72270. py = 0;
  72271. else if (py >= inputHeight)
  72272. py = inputHeight - 1;
  72273. var inputY = (inputHeight - py - 1);
  72274. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72275. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72276. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72277. return {
  72278. r: r,
  72279. g: g,
  72280. b: b
  72281. };
  72282. };
  72283. PanoramaToCubeMapTools.FACE_FRONT = [
  72284. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72285. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72286. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72287. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72288. ];
  72289. PanoramaToCubeMapTools.FACE_BACK = [
  72290. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72291. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72292. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72293. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72294. ];
  72295. PanoramaToCubeMapTools.FACE_RIGHT = [
  72296. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72297. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72298. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72299. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72300. ];
  72301. PanoramaToCubeMapTools.FACE_LEFT = [
  72302. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72303. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72304. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72305. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72306. ];
  72307. PanoramaToCubeMapTools.FACE_DOWN = [
  72308. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72309. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72310. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72311. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72312. ];
  72313. PanoramaToCubeMapTools.FACE_UP = [
  72314. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72315. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72316. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72317. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72318. ];
  72319. return PanoramaToCubeMapTools;
  72320. }());
  72321. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72322. })(BABYLON || (BABYLON = {}));
  72323. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72324. var BABYLON;
  72325. (function (BABYLON) {
  72326. ;
  72327. /**
  72328. * This groups tools to convert HDR texture to native colors array.
  72329. */
  72330. var HDRTools = /** @class */ (function () {
  72331. function HDRTools() {
  72332. }
  72333. HDRTools.Ldexp = function (mantissa, exponent) {
  72334. if (exponent > 1023) {
  72335. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72336. }
  72337. if (exponent < -1074) {
  72338. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72339. }
  72340. return mantissa * Math.pow(2, exponent);
  72341. };
  72342. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72343. if (exponent > 0) {
  72344. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72345. float32array[index + 0] = red * exponent;
  72346. float32array[index + 1] = green * exponent;
  72347. float32array[index + 2] = blue * exponent;
  72348. }
  72349. else {
  72350. float32array[index + 0] = 0;
  72351. float32array[index + 1] = 0;
  72352. float32array[index + 2] = 0;
  72353. }
  72354. };
  72355. HDRTools.readStringLine = function (uint8array, startIndex) {
  72356. var line = "";
  72357. var character = "";
  72358. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72359. character = String.fromCharCode(uint8array[i]);
  72360. if (character == "\n") {
  72361. break;
  72362. }
  72363. line += character;
  72364. }
  72365. return line;
  72366. };
  72367. /**
  72368. * Reads header information from an RGBE texture stored in a native array.
  72369. * More information on this format are available here:
  72370. * https://en.wikipedia.org/wiki/RGBE_image_format
  72371. *
  72372. * @param uint8array The binary file stored in native array.
  72373. * @return The header information.
  72374. */
  72375. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72376. var height = 0;
  72377. var width = 0;
  72378. var line = this.readStringLine(uint8array, 0);
  72379. if (line[0] != '#' || line[1] != '?') {
  72380. throw "Bad HDR Format.";
  72381. }
  72382. var endOfHeader = false;
  72383. var findFormat = false;
  72384. var lineIndex = 0;
  72385. do {
  72386. lineIndex += (line.length + 1);
  72387. line = this.readStringLine(uint8array, lineIndex);
  72388. if (line == "FORMAT=32-bit_rle_rgbe") {
  72389. findFormat = true;
  72390. }
  72391. else if (line.length == 0) {
  72392. endOfHeader = true;
  72393. }
  72394. } while (!endOfHeader);
  72395. if (!findFormat) {
  72396. throw "HDR Bad header format, unsupported FORMAT";
  72397. }
  72398. lineIndex += (line.length + 1);
  72399. line = this.readStringLine(uint8array, lineIndex);
  72400. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72401. var match = sizeRegexp.exec(line);
  72402. // TODO. Support +Y and -X if needed.
  72403. if (!match || match.length < 3) {
  72404. throw "HDR Bad header format, no size";
  72405. }
  72406. width = parseInt(match[2]);
  72407. height = parseInt(match[1]);
  72408. if (width < 8 || width > 0x7fff) {
  72409. throw "HDR Bad header format, unsupported size";
  72410. }
  72411. lineIndex += (line.length + 1);
  72412. return {
  72413. height: height,
  72414. width: width,
  72415. dataPosition: lineIndex
  72416. };
  72417. };
  72418. /**
  72419. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72420. * This RGBE texture needs to store the information as a panorama.
  72421. *
  72422. * More information on this format are available here:
  72423. * https://en.wikipedia.org/wiki/RGBE_image_format
  72424. *
  72425. * @param buffer The binary file stored in an array buffer.
  72426. * @param size The expected size of the extracted cubemap.
  72427. * @return The Cube Map information.
  72428. */
  72429. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72430. var uint8array = new Uint8Array(buffer);
  72431. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72432. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72433. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72434. return cubeMapData;
  72435. };
  72436. /**
  72437. * Returns the pixels data extracted from an RGBE texture.
  72438. * This pixels will be stored left to right up to down in the R G B order in one array.
  72439. *
  72440. * More information on this format are available here:
  72441. * https://en.wikipedia.org/wiki/RGBE_image_format
  72442. *
  72443. * @param uint8array The binary file stored in an array buffer.
  72444. * @param hdrInfo The header information of the file.
  72445. * @return The pixels data in RGB right to left up to down order.
  72446. */
  72447. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72448. // Keep for multi format supports.
  72449. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72450. };
  72451. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72452. var num_scanlines = hdrInfo.height;
  72453. var scanline_width = hdrInfo.width;
  72454. var a, b, c, d, count;
  72455. var dataIndex = hdrInfo.dataPosition;
  72456. var index = 0, endIndex = 0, i = 0;
  72457. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72458. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72459. // 3 channels of 4 bytes per pixel in float.
  72460. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72461. var resultArray = new Float32Array(resultBuffer);
  72462. // read in each successive scanline
  72463. while (num_scanlines > 0) {
  72464. a = uint8array[dataIndex++];
  72465. b = uint8array[dataIndex++];
  72466. c = uint8array[dataIndex++];
  72467. d = uint8array[dataIndex++];
  72468. if (a != 2 || b != 2 || (c & 0x80)) {
  72469. // this file is not run length encoded
  72470. throw "HDR Bad header format, not RLE";
  72471. }
  72472. if (((c << 8) | d) != scanline_width) {
  72473. throw "HDR Bad header format, wrong scan line width";
  72474. }
  72475. index = 0;
  72476. // read each of the four channels for the scanline into the buffer
  72477. for (i = 0; i < 4; i++) {
  72478. endIndex = (i + 1) * scanline_width;
  72479. while (index < endIndex) {
  72480. a = uint8array[dataIndex++];
  72481. b = uint8array[dataIndex++];
  72482. if (a > 128) {
  72483. // a run of the same value
  72484. count = a - 128;
  72485. if ((count == 0) || (count > endIndex - index)) {
  72486. throw "HDR Bad Format, bad scanline data (run)";
  72487. }
  72488. while (count-- > 0) {
  72489. scanLineArray[index++] = b;
  72490. }
  72491. }
  72492. else {
  72493. // a non-run
  72494. count = a;
  72495. if ((count == 0) || (count > endIndex - index)) {
  72496. throw "HDR Bad Format, bad scanline data (non-run)";
  72497. }
  72498. scanLineArray[index++] = b;
  72499. if (--count > 0) {
  72500. for (var j = 0; j < count; j++) {
  72501. scanLineArray[index++] = uint8array[dataIndex++];
  72502. }
  72503. }
  72504. }
  72505. }
  72506. }
  72507. // now convert data from buffer into floats
  72508. for (i = 0; i < scanline_width; i++) {
  72509. a = scanLineArray[i];
  72510. b = scanLineArray[i + scanline_width];
  72511. c = scanLineArray[i + 2 * scanline_width];
  72512. d = scanLineArray[i + 3 * scanline_width];
  72513. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72514. }
  72515. num_scanlines--;
  72516. }
  72517. return resultArray;
  72518. };
  72519. return HDRTools;
  72520. }());
  72521. BABYLON.HDRTools = HDRTools;
  72522. })(BABYLON || (BABYLON = {}));
  72523. //# sourceMappingURL=babylon.hdr.js.map
  72524. var BABYLON;
  72525. (function (BABYLON) {
  72526. /**
  72527. * This represents a texture coming from an HDR input.
  72528. *
  72529. * The only supported format is currently panorama picture stored in RGBE format.
  72530. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72531. */
  72532. var HDRCubeTexture = /** @class */ (function (_super) {
  72533. __extends(HDRCubeTexture, _super);
  72534. /**
  72535. * Instantiates an HDRTexture from the following parameters.
  72536. *
  72537. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72538. * @param scene The scene the texture will be used in
  72539. * @param size The cubemap 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.
  72540. * @param noMipmap Forces to not generate the mipmap if true
  72541. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72542. * @param useInGammaSpace 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)
  72543. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72544. */
  72545. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72546. if (noMipmap === void 0) { noMipmap = false; }
  72547. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72548. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72549. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72550. if (onLoad === void 0) { onLoad = null; }
  72551. if (onError === void 0) { onError = null; }
  72552. var _this = _super.call(this, scene) || this;
  72553. _this._useInGammaSpace = false;
  72554. _this._generateHarmonics = true;
  72555. _this._isBABYLONPreprocessed = false;
  72556. _this._onLoad = null;
  72557. _this._onError = null;
  72558. /**
  72559. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72560. */
  72561. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72562. /**
  72563. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72564. * This is usefull at run time to apply the good shader.
  72565. */
  72566. _this.isPMREM = false;
  72567. _this._isBlocking = true;
  72568. /**
  72569. * Gets or sets the center of the bounding box associated with the cube texture
  72570. * It must define where the camera used to render the texture was set
  72571. */
  72572. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72573. if (!url) {
  72574. return _this;
  72575. }
  72576. _this.name = url;
  72577. _this.url = url;
  72578. _this.hasAlpha = false;
  72579. _this.isCube = true;
  72580. _this._textureMatrix = BABYLON.Matrix.Identity();
  72581. _this._onLoad = onLoad;
  72582. _this._onError = onError;
  72583. _this.gammaSpace = false;
  72584. var caps = scene.getEngine().getCaps();
  72585. if (size) {
  72586. _this._isBABYLONPreprocessed = false;
  72587. _this._noMipmap = noMipmap;
  72588. _this._size = size;
  72589. _this._useInGammaSpace = useInGammaSpace;
  72590. _this._usePMREMGenerator = usePMREMGenerator &&
  72591. caps.textureLOD &&
  72592. caps.textureFloat &&
  72593. !_this._useInGammaSpace;
  72594. }
  72595. else {
  72596. _this._isBABYLONPreprocessed = true;
  72597. _this._noMipmap = false;
  72598. _this._useInGammaSpace = false;
  72599. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72600. !_this._useInGammaSpace;
  72601. }
  72602. _this.isPMREM = _this._usePMREMGenerator;
  72603. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72604. if (!_this._texture) {
  72605. if (!scene.useDelayedTextureLoading) {
  72606. _this.loadTexture();
  72607. }
  72608. else {
  72609. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72610. }
  72611. }
  72612. return _this;
  72613. }
  72614. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72615. /**
  72616. * Gets wether or not the texture is blocking during loading.
  72617. */
  72618. get: function () {
  72619. return this._isBlocking;
  72620. },
  72621. /**
  72622. * Sets wether or not the texture is blocking during loading.
  72623. */
  72624. set: function (value) {
  72625. this._isBlocking = value;
  72626. },
  72627. enumerable: true,
  72628. configurable: true
  72629. });
  72630. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72631. get: function () {
  72632. return this._boundingBoxSize;
  72633. },
  72634. /**
  72635. * Gets or sets the size of the bounding box associated with the cube texture
  72636. * When defined, the cubemap will switch to local mode
  72637. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72638. * @example https://www.babylonjs-playground.com/#RNASML
  72639. */
  72640. set: function (value) {
  72641. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72642. return;
  72643. }
  72644. this._boundingBoxSize = value;
  72645. var scene = this.getScene();
  72646. if (scene) {
  72647. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72648. }
  72649. },
  72650. enumerable: true,
  72651. configurable: true
  72652. });
  72653. /**
  72654. * Occurs when the file is a preprocessed .babylon.hdr file.
  72655. */
  72656. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72657. var _this = this;
  72658. var mipLevels = 0;
  72659. var floatArrayView = null;
  72660. var scene = this.getScene();
  72661. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72662. var mips = new Array();
  72663. if (!floatArrayView) {
  72664. return mips;
  72665. }
  72666. var startIndex = 30;
  72667. for (var level = 0; level < mipLevels; level++) {
  72668. mips.push([]);
  72669. // Fill each pixel of the mip level.
  72670. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72671. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72672. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72673. mips[level].push(faceData);
  72674. startIndex += faceSize;
  72675. }
  72676. }
  72677. return mips;
  72678. } : null;
  72679. var callback = function (buffer) {
  72680. var scene = _this.getScene();
  72681. if (!scene) {
  72682. return null;
  72683. }
  72684. // Create Native Array Views
  72685. var intArrayView = new Int32Array(buffer);
  72686. floatArrayView = new Float32Array(buffer);
  72687. // Fill header.
  72688. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72689. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72690. // Update Texture Information.
  72691. if (!_this._texture) {
  72692. return null;
  72693. }
  72694. _this._texture.updateSize(_this._size, _this._size);
  72695. // Fill polynomial information.
  72696. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72697. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72698. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72699. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72700. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72701. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72702. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72703. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72704. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72705. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72706. _this.sphericalPolynomial = sphericalPolynomial;
  72707. // Fill pixel data.
  72708. mipLevels = intArrayView[29]; // Number of mip levels.
  72709. var startIndex = 30;
  72710. var data = [];
  72711. var faceSize = Math.pow(_this._size, 2) * 3;
  72712. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72713. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72714. startIndex += faceSize;
  72715. }
  72716. var results = [];
  72717. var byteArray = null;
  72718. // Push each faces.
  72719. for (var k = 0; k < 6; k++) {
  72720. var dataFace = null;
  72721. // To be deprecated.
  72722. if (version === 1) {
  72723. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72724. dataFace = data[j];
  72725. }
  72726. // If special cases.
  72727. if (!mipmapGenerator && dataFace) {
  72728. if (!scene.getEngine().getCaps().textureFloat) {
  72729. // 3 channels of 1 bytes per pixel in bytes.
  72730. var byteBuffer = new ArrayBuffer(faceSize);
  72731. byteArray = new Uint8Array(byteBuffer);
  72732. }
  72733. for (var i = 0; i < _this._size * _this._size; i++) {
  72734. // Put in gamma space if requested.
  72735. if (_this._useInGammaSpace) {
  72736. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72737. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72738. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72739. }
  72740. // Convert to int texture for fallback.
  72741. if (byteArray) {
  72742. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72743. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72744. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72745. // May use luminance instead if the result is not accurate.
  72746. var max = Math.max(Math.max(r, g), b);
  72747. if (max > 255) {
  72748. var scale = 255 / max;
  72749. r *= scale;
  72750. g *= scale;
  72751. b *= scale;
  72752. }
  72753. byteArray[(i * 3) + 0] = r;
  72754. byteArray[(i * 3) + 1] = g;
  72755. byteArray[(i * 3) + 2] = b;
  72756. }
  72757. }
  72758. }
  72759. // Fill the array accordingly.
  72760. if (byteArray) {
  72761. results.push(byteArray);
  72762. }
  72763. else {
  72764. results.push(dataFace);
  72765. }
  72766. }
  72767. return results;
  72768. };
  72769. if (scene) {
  72770. 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, mipmapGenerator, this._onLoad, this._onError);
  72771. }
  72772. };
  72773. /**
  72774. * Occurs when the file is raw .hdr file.
  72775. */
  72776. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72777. var _this = this;
  72778. var callback = function (buffer) {
  72779. var scene = _this.getScene();
  72780. if (!scene) {
  72781. return null;
  72782. }
  72783. // Extract the raw linear data.
  72784. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72785. // Generate harmonics if needed.
  72786. if (_this._generateHarmonics) {
  72787. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72788. _this.sphericalPolynomial = sphericalPolynomial;
  72789. }
  72790. var results = [];
  72791. var byteArray = null;
  72792. // Push each faces.
  72793. for (var j = 0; j < 6; j++) {
  72794. // Create uintarray fallback.
  72795. if (!scene.getEngine().getCaps().textureFloat) {
  72796. // 3 channels of 1 bytes per pixel in bytes.
  72797. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72798. byteArray = new Uint8Array(byteBuffer);
  72799. }
  72800. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72801. // If special cases.
  72802. if (_this._useInGammaSpace || byteArray) {
  72803. for (var i = 0; i < _this._size * _this._size; i++) {
  72804. // Put in gamma space if requested.
  72805. if (_this._useInGammaSpace) {
  72806. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72807. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72808. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72809. }
  72810. // Convert to int texture for fallback.
  72811. if (byteArray) {
  72812. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72813. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72814. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72815. // May use luminance instead if the result is not accurate.
  72816. var max = Math.max(Math.max(r, g), b);
  72817. if (max > 255) {
  72818. var scale = 255 / max;
  72819. r *= scale;
  72820. g *= scale;
  72821. b *= scale;
  72822. }
  72823. byteArray[(i * 3) + 0] = r;
  72824. byteArray[(i * 3) + 1] = g;
  72825. byteArray[(i * 3) + 2] = b;
  72826. }
  72827. }
  72828. }
  72829. if (byteArray) {
  72830. results.push(byteArray);
  72831. }
  72832. else {
  72833. results.push(dataFace);
  72834. }
  72835. }
  72836. return results;
  72837. };
  72838. var mipmapGenerator = null;
  72839. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72840. // if (!this._noMipmap &&
  72841. // this._usePMREMGenerator) {
  72842. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72843. // // Custom setup of the generator matching with the PBR shader values.
  72844. // var generator = new BABYLON.PMREMGenerator(data,
  72845. // this._size,
  72846. // this._size,
  72847. // 0,
  72848. // 3,
  72849. // this.getScene().getEngine().getCaps().textureFloat,
  72850. // 2048,
  72851. // 0.25,
  72852. // false,
  72853. // true);
  72854. // return generator.filterCubeMap();
  72855. // };
  72856. // }
  72857. var scene = this.getScene();
  72858. if (scene) {
  72859. 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, mipmapGenerator, this._onLoad, this._onError);
  72860. }
  72861. };
  72862. /**
  72863. * Starts the loading process of the texture.
  72864. */
  72865. HDRCubeTexture.prototype.loadTexture = function () {
  72866. if (this._isBABYLONPreprocessed) {
  72867. this.loadBabylonTexture();
  72868. }
  72869. else {
  72870. this.loadHDRTexture();
  72871. }
  72872. };
  72873. HDRCubeTexture.prototype.clone = function () {
  72874. var scene = this.getScene();
  72875. if (!scene) {
  72876. return this;
  72877. }
  72878. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72879. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72880. // Base texture
  72881. newTexture.level = this.level;
  72882. newTexture.wrapU = this.wrapU;
  72883. newTexture.wrapV = this.wrapV;
  72884. newTexture.coordinatesIndex = this.coordinatesIndex;
  72885. newTexture.coordinatesMode = this.coordinatesMode;
  72886. return newTexture;
  72887. };
  72888. // Methods
  72889. HDRCubeTexture.prototype.delayLoad = function () {
  72890. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72891. return;
  72892. }
  72893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72894. this._texture = this._getFromCache(this.url, this._noMipmap);
  72895. if (!this._texture) {
  72896. this.loadTexture();
  72897. }
  72898. };
  72899. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72900. return this._textureMatrix;
  72901. };
  72902. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72903. this._textureMatrix = value;
  72904. };
  72905. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72906. var texture = null;
  72907. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72908. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72909. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72910. texture.name = parsedTexture.name;
  72911. texture.hasAlpha = parsedTexture.hasAlpha;
  72912. texture.level = parsedTexture.level;
  72913. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72914. texture.isBlocking = parsedTexture.isBlocking;
  72915. }
  72916. if (texture) {
  72917. if (parsedTexture.boundingBoxPosition) {
  72918. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72919. }
  72920. if (parsedTexture.boundingBoxSize) {
  72921. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72922. }
  72923. }
  72924. return texture;
  72925. };
  72926. HDRCubeTexture.prototype.serialize = function () {
  72927. if (!this.name) {
  72928. return null;
  72929. }
  72930. var serializationObject = {};
  72931. serializationObject.name = this.name;
  72932. serializationObject.hasAlpha = this.hasAlpha;
  72933. serializationObject.isCube = true;
  72934. serializationObject.level = this.level;
  72935. serializationObject.size = this._size;
  72936. serializationObject.coordinatesMode = this.coordinatesMode;
  72937. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72938. serializationObject.generateHarmonics = this._generateHarmonics;
  72939. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72940. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72941. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72942. serializationObject.noMipmap = this._noMipmap;
  72943. serializationObject.isBlocking = this._isBlocking;
  72944. return serializationObject;
  72945. };
  72946. /**
  72947. * Saves as a file the data contained in the texture in a binary format.
  72948. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72949. * as the spherical used in the lighting.
  72950. * @param url The HDR file url.
  72951. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72952. * @param onError Method called if any error happens during download.
  72953. * @return The packed binary data.
  72954. */
  72955. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72956. if (onError === void 0) { onError = null; }
  72957. var callback = function (buffer) {
  72958. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72959. // Returns a URL you can use as a href.
  72960. var objUrl = window.URL.createObjectURL(data);
  72961. // Simulates a link to it and click to dowload.
  72962. var a = document.createElement("a");
  72963. document.body.appendChild(a);
  72964. a.style.display = "none";
  72965. a.href = objUrl;
  72966. a.download = "envmap.babylon.hdr";
  72967. a.click();
  72968. };
  72969. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72970. };
  72971. /**
  72972. * Serializes the data contained in the texture in a binary format.
  72973. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72974. * as the spherical used in the lighting.
  72975. * @param url The HDR file url.
  72976. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72977. * @param onError Method called if any error happens during download.
  72978. * @return The packed binary data.
  72979. */
  72980. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72981. if (onError === void 0) { onError = null; }
  72982. // Needs the url tho create the texture.
  72983. if (!url) {
  72984. return;
  72985. }
  72986. // Check Power of two size.
  72987. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72988. return;
  72989. }
  72990. // Coming Back in 3.x.
  72991. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72992. };
  72993. HDRCubeTexture._facesMapping = [
  72994. "right",
  72995. "left",
  72996. "up",
  72997. "down",
  72998. "front",
  72999. "back"
  73000. ];
  73001. return HDRCubeTexture;
  73002. }(BABYLON.BaseTexture));
  73003. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73004. })(BABYLON || (BABYLON = {}));
  73005. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73006. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73007. // Huge respect for a such great lib.
  73008. // Earcut license:
  73009. // Copyright (c) 2016, Mapbox
  73010. //
  73011. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73012. // with or without fee is hereby granted, provided that the above copyright notice
  73013. // and this permission notice appear in all copies.
  73014. //
  73015. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73016. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73017. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73018. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73019. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73020. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73021. // THIS SOFTWARE.
  73022. var Earcut;
  73023. (function (Earcut) {
  73024. /**
  73025. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73026. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73027. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  73028. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73029. */
  73030. function earcut(data, holeIndices, dim) {
  73031. dim = dim || 2;
  73032. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73033. if (!outerNode)
  73034. return triangles;
  73035. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73036. if (hasHoles)
  73037. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73038. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73039. if (data.length > 80 * dim) {
  73040. minX = maxX = data[0];
  73041. minY = maxY = data[1];
  73042. for (var i = dim; i < outerLen; i += dim) {
  73043. x = data[i];
  73044. y = data[i + 1];
  73045. if (x < minX)
  73046. minX = x;
  73047. if (y < minY)
  73048. minY = y;
  73049. if (x > maxX)
  73050. maxX = x;
  73051. if (y > maxY)
  73052. maxY = y;
  73053. }
  73054. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73055. size = Math.max(maxX - minX, maxY - minY);
  73056. }
  73057. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73058. return triangles;
  73059. }
  73060. Earcut.earcut = earcut;
  73061. var Node = /** @class */ (function () {
  73062. function Node(i, x, y) {
  73063. this.i = i;
  73064. this.x = x;
  73065. this.y = y;
  73066. this.prev = null;
  73067. this.next = null;
  73068. this.z = null;
  73069. this.prevZ = null;
  73070. this.nextZ = null;
  73071. this.steiner = false;
  73072. }
  73073. return Node;
  73074. }());
  73075. // create a circular doubly linked list from polygon points in the specified winding order
  73076. function linkedList(data, start, end, dim, clockwise) {
  73077. var i, last = null;
  73078. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73079. for (i = start; i < end; i += dim)
  73080. last = insertNode(i, data[i], data[i + 1], last);
  73081. }
  73082. else {
  73083. for (i = end - dim; i >= start; i -= dim)
  73084. last = insertNode(i, data[i], data[i + 1], last);
  73085. }
  73086. if (last && equals(last, last.next)) {
  73087. removeNode(last);
  73088. last = last.next;
  73089. }
  73090. return last;
  73091. }
  73092. // eliminate colinear or duplicate points
  73093. function filterPoints(start, end) {
  73094. if (!start)
  73095. return start;
  73096. if (!end)
  73097. end = start;
  73098. var p = start, again;
  73099. do {
  73100. again = false;
  73101. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73102. removeNode(p);
  73103. p = end = p.prev;
  73104. if (p === p.next)
  73105. return undefined;
  73106. again = true;
  73107. }
  73108. else {
  73109. p = p.next;
  73110. }
  73111. } while (again || p !== end);
  73112. return end;
  73113. }
  73114. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73115. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73116. if (!ear)
  73117. return;
  73118. // interlink polygon nodes in z-order
  73119. if (!pass && size)
  73120. indexCurve(ear, minX, minY, size);
  73121. var stop = ear, prev, next;
  73122. // iterate through ears, slicing them one by one
  73123. while (ear.prev !== ear.next) {
  73124. prev = ear.prev;
  73125. next = ear.next;
  73126. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73127. // cut off the triangle
  73128. triangles.push(prev.i / dim);
  73129. triangles.push(ear.i / dim);
  73130. triangles.push(next.i / dim);
  73131. removeNode(ear);
  73132. // skipping the next vertice leads to less sliver triangles
  73133. ear = next.next;
  73134. stop = next.next;
  73135. continue;
  73136. }
  73137. ear = next;
  73138. // if we looped through the whole remaining polygon and can't find any more ears
  73139. if (ear === stop) {
  73140. // try filtering points and slicing again
  73141. if (!pass) {
  73142. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73143. // if this didn't work, try curing all small self-intersections locally
  73144. }
  73145. else if (pass === 1) {
  73146. ear = cureLocalIntersections(ear, triangles, dim);
  73147. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73148. // as a last resort, try splitting the remaining polygon into two
  73149. }
  73150. else if (pass === 2) {
  73151. splitEarcut(ear, triangles, dim, minX, minY, size);
  73152. }
  73153. break;
  73154. }
  73155. }
  73156. }
  73157. // check whether a polygon node forms a valid ear with adjacent nodes
  73158. function isEar(ear) {
  73159. var a = ear.prev, b = ear, c = ear.next;
  73160. if (area(a, b, c) >= 0)
  73161. return false; // reflex, can't be an ear
  73162. // now make sure we don't have other points inside the potential ear
  73163. var p = ear.next.next;
  73164. while (p !== ear.prev) {
  73165. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73166. area(p.prev, p, p.next) >= 0)
  73167. return false;
  73168. p = p.next;
  73169. }
  73170. return true;
  73171. }
  73172. function isEarHashed(ear, minX, minY, size) {
  73173. var a = ear.prev, b = ear, c = ear.next;
  73174. if (area(a, b, c) >= 0)
  73175. return false; // reflex, can't be an ear
  73176. // triangle bbox; min & max are calculated like this for speed
  73177. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  73178. // z-order range for the current triangle bbox;
  73179. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73180. // first look for points inside the triangle in increasing z-order
  73181. var p = ear.nextZ;
  73182. while (p && p.z <= maxZ) {
  73183. if (p !== ear.prev &&
  73184. p !== ear.next &&
  73185. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73186. area(p.prev, p, p.next) >= 0)
  73187. return false;
  73188. p = p.nextZ;
  73189. }
  73190. // then look for points in decreasing z-order
  73191. p = ear.prevZ;
  73192. while (p && p.z >= minZ) {
  73193. if (p !== ear.prev &&
  73194. p !== ear.next &&
  73195. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73196. area(p.prev, p, p.next) >= 0)
  73197. return false;
  73198. p = p.prevZ;
  73199. }
  73200. return true;
  73201. }
  73202. // go through all polygon nodes and cure small local self-intersections
  73203. function cureLocalIntersections(start, triangles, dim) {
  73204. var p = start;
  73205. do {
  73206. var a = p.prev, b = p.next.next;
  73207. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73208. triangles.push(a.i / dim);
  73209. triangles.push(p.i / dim);
  73210. triangles.push(b.i / dim);
  73211. // remove two nodes involved
  73212. removeNode(p);
  73213. removeNode(p.next);
  73214. p = start = b;
  73215. }
  73216. p = p.next;
  73217. } while (p !== start);
  73218. return p;
  73219. }
  73220. // try splitting polygon into two and triangulate them independently
  73221. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73222. // look for a valid diagonal that divides the polygon into two
  73223. var a = start;
  73224. do {
  73225. var b = a.next.next;
  73226. while (b !== a.prev) {
  73227. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73228. // split the polygon in two by the diagonal
  73229. var c = splitPolygon(a, b);
  73230. // filter colinear points around the cuts
  73231. a = filterPoints(a, a.next);
  73232. c = filterPoints(c, c.next);
  73233. // run earcut on each half
  73234. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73235. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73236. return;
  73237. }
  73238. b = b.next;
  73239. }
  73240. a = a.next;
  73241. } while (a !== start);
  73242. }
  73243. // link every hole into the outer loop, producing a single-ring polygon without holes
  73244. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73245. var queue = [], i, len, start, end, list;
  73246. for (i = 0, len = holeIndices.length; i < len; i++) {
  73247. start = holeIndices[i] * dim;
  73248. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73249. list = linkedList(data, start, end, dim, false);
  73250. if (list === list.next)
  73251. list.steiner = true;
  73252. queue.push(getLeftmost(list));
  73253. }
  73254. queue.sort(compareX);
  73255. // process holes from left to right
  73256. for (i = 0; i < queue.length; i++) {
  73257. eliminateHole(queue[i], outerNode);
  73258. outerNode = filterPoints(outerNode, outerNode.next);
  73259. }
  73260. return outerNode;
  73261. }
  73262. function compareX(a, b) {
  73263. return a.x - b.x;
  73264. }
  73265. // find a bridge between vertices that connects hole with an outer ring and and link it
  73266. function eliminateHole(hole, outerNode) {
  73267. outerNode = findHoleBridge(hole, outerNode);
  73268. if (outerNode) {
  73269. var b = splitPolygon(outerNode, hole);
  73270. filterPoints(b, b.next);
  73271. }
  73272. }
  73273. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73274. function findHoleBridge(hole, outerNode) {
  73275. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73276. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73277. // segment's endpoint with lesser x will be potential connection point
  73278. do {
  73279. if (hy <= p.y && hy >= p.next.y) {
  73280. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73281. if (x <= hx && x > qx) {
  73282. qx = x;
  73283. if (x === hx) {
  73284. if (hy === p.y)
  73285. return p;
  73286. if (hy === p.next.y)
  73287. return p.next;
  73288. }
  73289. m = p.x < p.next.x ? p : p.next;
  73290. }
  73291. }
  73292. p = p.next;
  73293. } while (p !== outerNode);
  73294. if (!m)
  73295. return null;
  73296. if (hx === qx)
  73297. return m.prev; // hole touches outer segment; pick lower endpoint
  73298. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73299. // if there are no points found, we have a valid connection;
  73300. // otherwise choose the point of the minimum angle with the ray as connection point
  73301. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73302. p = m.next;
  73303. while (p !== stop) {
  73304. if (hx >= p.x &&
  73305. p.x >= mx &&
  73306. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73307. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73308. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73309. m = p;
  73310. tanMin = tan;
  73311. }
  73312. }
  73313. p = p.next;
  73314. }
  73315. return m;
  73316. }
  73317. // interlink polygon nodes in z-order
  73318. function indexCurve(start, minX, minY, size) {
  73319. var p = start;
  73320. do {
  73321. if (p.z === null)
  73322. p.z = zOrder(p.x, p.y, minX, minY, size);
  73323. p.prevZ = p.prev;
  73324. p.nextZ = p.next;
  73325. p = p.next;
  73326. } while (p !== start);
  73327. p.prevZ.nextZ = null;
  73328. p.prevZ = null;
  73329. sortLinked(p);
  73330. }
  73331. // Simon Tatham's linked list merge sort algorithm
  73332. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73333. function sortLinked(list) {
  73334. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73335. do {
  73336. p = list;
  73337. list = null;
  73338. tail = null;
  73339. numMerges = 0;
  73340. while (p) {
  73341. numMerges++;
  73342. q = p;
  73343. pSize = 0;
  73344. for (i = 0; i < inSize; i++) {
  73345. pSize++;
  73346. q = q.nextZ;
  73347. if (!q)
  73348. break;
  73349. }
  73350. qSize = inSize;
  73351. while (pSize > 0 || (qSize > 0 && q)) {
  73352. if (pSize === 0) {
  73353. e = q;
  73354. q = q.nextZ;
  73355. qSize--;
  73356. }
  73357. else if (qSize === 0 || !q) {
  73358. e = p;
  73359. p = p.nextZ;
  73360. pSize--;
  73361. }
  73362. else if (p.z <= q.z) {
  73363. e = p;
  73364. p = p.nextZ;
  73365. pSize--;
  73366. }
  73367. else {
  73368. e = q;
  73369. q = q.nextZ;
  73370. qSize--;
  73371. }
  73372. if (tail)
  73373. tail.nextZ = e;
  73374. else
  73375. list = e;
  73376. e.prevZ = tail;
  73377. tail = e;
  73378. }
  73379. p = q;
  73380. }
  73381. tail.nextZ = null;
  73382. inSize *= 2;
  73383. } while (numMerges > 1);
  73384. return list;
  73385. }
  73386. // z-order of a point given coords and size of the data bounding box
  73387. function zOrder(x, y, minX, minY, size) {
  73388. // coords are transformed into non-negative 15-bit integer range
  73389. x = 32767 * (x - minX) / size;
  73390. y = 32767 * (y - minY) / size;
  73391. x = (x | (x << 8)) & 0x00FF00FF;
  73392. x = (x | (x << 4)) & 0x0F0F0F0F;
  73393. x = (x | (x << 2)) & 0x33333333;
  73394. x = (x | (x << 1)) & 0x55555555;
  73395. y = (y | (y << 8)) & 0x00FF00FF;
  73396. y = (y | (y << 4)) & 0x0F0F0F0F;
  73397. y = (y | (y << 2)) & 0x33333333;
  73398. y = (y | (y << 1)) & 0x55555555;
  73399. return x | (y << 1);
  73400. }
  73401. // find the leftmost node of a polygon ring
  73402. function getLeftmost(start) {
  73403. var p = start, leftmost = start;
  73404. do {
  73405. if (p.x < leftmost.x)
  73406. leftmost = p;
  73407. p = p.next;
  73408. } while (p !== start);
  73409. return leftmost;
  73410. }
  73411. // check if a point lies within a convex triangle
  73412. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73413. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73414. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73415. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73416. }
  73417. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73418. function isValidDiagonal(a, b) {
  73419. return a.next.i !== b.i &&
  73420. a.prev.i !== b.i &&
  73421. !intersectsPolygon(a, b) &&
  73422. locallyInside(a, b) &&
  73423. locallyInside(b, a) &&
  73424. middleInside(a, b);
  73425. }
  73426. // signed area of a triangle
  73427. function area(p, q, r) {
  73428. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73429. }
  73430. // check if two points are equal
  73431. function equals(p1, p2) {
  73432. return p1.x === p2.x && p1.y === p2.y;
  73433. }
  73434. // check if two segments intersect
  73435. function intersects(p1, q1, p2, q2) {
  73436. if ((equals(p1, q1) && equals(p2, q2)) ||
  73437. (equals(p1, q2) && equals(p2, q1)))
  73438. return true;
  73439. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73440. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73441. }
  73442. // check if a polygon diagonal intersects any polygon segments
  73443. function intersectsPolygon(a, b) {
  73444. var p = a;
  73445. do {
  73446. if (p.i !== a.i &&
  73447. p.next.i !== a.i &&
  73448. p.i !== b.i &&
  73449. p.next.i !== b.i &&
  73450. intersects(p, p.next, a, b))
  73451. return true;
  73452. p = p.next;
  73453. } while (p !== a);
  73454. return false;
  73455. }
  73456. // check if a polygon diagonal is locally inside the polygon
  73457. function locallyInside(a, b) {
  73458. return area(a.prev, a, a.next) < 0
  73459. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73460. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73461. }
  73462. // check if the middle point of a polygon diagonal is inside the polygon
  73463. function middleInside(a, b) {
  73464. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73465. do {
  73466. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73467. inside = !inside;
  73468. p = p.next;
  73469. } while (p !== a);
  73470. return inside;
  73471. }
  73472. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73473. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73474. function splitPolygon(a, b) {
  73475. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  73476. a.next = b;
  73477. b.prev = a;
  73478. a2.next = an;
  73479. an.prev = a2;
  73480. b2.next = a2;
  73481. a2.prev = b2;
  73482. bp.next = b2;
  73483. b2.prev = bp;
  73484. return b2;
  73485. }
  73486. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73487. function insertNode(i, x, y, last) {
  73488. var p = new Node(i, x, y);
  73489. if (!last) {
  73490. p.prev = p;
  73491. p.next = p;
  73492. }
  73493. else {
  73494. p.next = last.next;
  73495. p.prev = last;
  73496. last.next.prev = p;
  73497. last.next = p;
  73498. }
  73499. return p;
  73500. }
  73501. function removeNode(p) {
  73502. p.next.prev = p.prev;
  73503. p.prev.next = p.next;
  73504. if (p.prevZ)
  73505. p.prevZ.nextZ = p.nextZ;
  73506. if (p.nextZ)
  73507. p.nextZ.prevZ = p.prevZ;
  73508. }
  73509. /**
  73510. * return a percentage difference between the polygon area and its triangulation area;
  73511. * used to verify correctness of triangulation
  73512. */
  73513. function deviation(data, holeIndices, dim, triangles) {
  73514. var hasHoles = holeIndices && holeIndices.length;
  73515. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73516. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73517. if (hasHoles) {
  73518. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73519. var start = holeIndices[i] * dim;
  73520. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73521. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73522. }
  73523. }
  73524. var trianglesArea = 0;
  73525. for (i = 0; i < triangles.length; i += 3) {
  73526. var a = triangles[i] * dim;
  73527. var b = triangles[i + 1] * dim;
  73528. var c = triangles[i + 2] * dim;
  73529. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73530. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73531. }
  73532. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73533. }
  73534. Earcut.deviation = deviation;
  73535. ;
  73536. function signedArea(data, start, end, dim) {
  73537. var sum = 0;
  73538. for (var i = start, j = end - dim; i < end; i += dim) {
  73539. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73540. j = i;
  73541. }
  73542. return sum;
  73543. }
  73544. /**
  73545. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73546. */
  73547. function flatten(data) {
  73548. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73549. for (var i = 0; i < data.length; i++) {
  73550. for (var j = 0; j < data[i].length; j++) {
  73551. for (var d = 0; d < dim; d++)
  73552. result.vertices.push(data[i][j][d]);
  73553. }
  73554. if (i > 0) {
  73555. holeIndex += data[i - 1].length;
  73556. result.holes.push(holeIndex);
  73557. }
  73558. }
  73559. return result;
  73560. }
  73561. Earcut.flatten = flatten;
  73562. ;
  73563. })(Earcut || (Earcut = {}));
  73564. //# sourceMappingURL=babylon.earcut.js.map
  73565. var BABYLON;
  73566. (function (BABYLON) {
  73567. var IndexedVector2 = /** @class */ (function (_super) {
  73568. __extends(IndexedVector2, _super);
  73569. function IndexedVector2(original, index) {
  73570. var _this = _super.call(this, original.x, original.y) || this;
  73571. _this.index = index;
  73572. return _this;
  73573. }
  73574. return IndexedVector2;
  73575. }(BABYLON.Vector2));
  73576. var PolygonPoints = /** @class */ (function () {
  73577. function PolygonPoints() {
  73578. this.elements = new Array();
  73579. }
  73580. PolygonPoints.prototype.add = function (originalPoints) {
  73581. var _this = this;
  73582. var result = new Array();
  73583. originalPoints.forEach(function (point) {
  73584. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73585. var newPoint = new IndexedVector2(point, _this.elements.length);
  73586. result.push(newPoint);
  73587. _this.elements.push(newPoint);
  73588. }
  73589. });
  73590. return result;
  73591. };
  73592. PolygonPoints.prototype.computeBounds = function () {
  73593. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73594. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73595. this.elements.forEach(function (point) {
  73596. // x
  73597. if (point.x < lmin.x) {
  73598. lmin.x = point.x;
  73599. }
  73600. else if (point.x > lmax.x) {
  73601. lmax.x = point.x;
  73602. }
  73603. // y
  73604. if (point.y < lmin.y) {
  73605. lmin.y = point.y;
  73606. }
  73607. else if (point.y > lmax.y) {
  73608. lmax.y = point.y;
  73609. }
  73610. });
  73611. return {
  73612. min: lmin,
  73613. max: lmax,
  73614. width: lmax.x - lmin.x,
  73615. height: lmax.y - lmin.y
  73616. };
  73617. };
  73618. return PolygonPoints;
  73619. }());
  73620. var Polygon = /** @class */ (function () {
  73621. function Polygon() {
  73622. }
  73623. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73624. return [
  73625. new BABYLON.Vector2(xmin, ymin),
  73626. new BABYLON.Vector2(xmax, ymin),
  73627. new BABYLON.Vector2(xmax, ymax),
  73628. new BABYLON.Vector2(xmin, ymax)
  73629. ];
  73630. };
  73631. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73632. if (cx === void 0) { cx = 0; }
  73633. if (cy === void 0) { cy = 0; }
  73634. if (numberOfSides === void 0) { numberOfSides = 32; }
  73635. var result = new Array();
  73636. var angle = 0;
  73637. var increment = (Math.PI * 2) / numberOfSides;
  73638. for (var i = 0; i < numberOfSides; i++) {
  73639. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73640. angle -= increment;
  73641. }
  73642. return result;
  73643. };
  73644. Polygon.Parse = function (input) {
  73645. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73646. var i, result = [];
  73647. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73648. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73649. }
  73650. return result;
  73651. };
  73652. Polygon.StartingAt = function (x, y) {
  73653. return BABYLON.Path2.StartingAt(x, y);
  73654. };
  73655. return Polygon;
  73656. }());
  73657. BABYLON.Polygon = Polygon;
  73658. var PolygonMeshBuilder = /** @class */ (function () {
  73659. function PolygonMeshBuilder(name, contours, scene) {
  73660. this._points = new PolygonPoints();
  73661. this._outlinepoints = new PolygonPoints();
  73662. this._holes = new Array();
  73663. this._epoints = new Array();
  73664. this._eholes = new Array();
  73665. this._name = name;
  73666. this._scene = scene;
  73667. var points;
  73668. if (contours instanceof BABYLON.Path2) {
  73669. points = contours.getPoints();
  73670. }
  73671. else {
  73672. points = contours;
  73673. }
  73674. this._addToepoint(points);
  73675. this._points.add(points);
  73676. this._outlinepoints.add(points);
  73677. }
  73678. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73679. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73680. var p = points_1[_i];
  73681. this._epoints.push(p.x, p.y);
  73682. }
  73683. };
  73684. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73685. this._points.add(hole);
  73686. var holepoints = new PolygonPoints();
  73687. holepoints.add(hole);
  73688. this._holes.push(holepoints);
  73689. this._eholes.push(this._epoints.length / 2);
  73690. this._addToepoint(hole);
  73691. return this;
  73692. };
  73693. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73694. var _this = this;
  73695. if (updatable === void 0) { updatable = false; }
  73696. if (depth === void 0) { depth = 0; }
  73697. var result = new BABYLON.Mesh(this._name, this._scene);
  73698. var normals = new Array();
  73699. var positions = new Array();
  73700. var uvs = new Array();
  73701. var bounds = this._points.computeBounds();
  73702. this._points.elements.forEach(function (p) {
  73703. normals.push(0, 1.0, 0);
  73704. positions.push(p.x, 0, p.y);
  73705. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73706. });
  73707. var indices = new Array();
  73708. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73709. for (var i = 0; i < res.length; i++) {
  73710. indices.push(res[i]);
  73711. }
  73712. if (depth > 0) {
  73713. var positionscount = (positions.length / 3); //get the current pointcount
  73714. this._points.elements.forEach(function (p) {
  73715. normals.push(0, -1.0, 0);
  73716. positions.push(p.x, -depth, p.y);
  73717. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73718. });
  73719. var totalCount = indices.length;
  73720. for (var i = 0; i < totalCount; i += 3) {
  73721. var i0 = indices[i + 0];
  73722. var i1 = indices[i + 1];
  73723. var i2 = indices[i + 2];
  73724. indices.push(i2 + positionscount);
  73725. indices.push(i1 + positionscount);
  73726. indices.push(i0 + positionscount);
  73727. }
  73728. //Add the sides
  73729. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73730. this._holes.forEach(function (hole) {
  73731. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73732. });
  73733. }
  73734. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73735. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73736. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73737. result.setIndices(indices);
  73738. return result;
  73739. };
  73740. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73741. var StartIndex = positions.length / 3;
  73742. var ulength = 0;
  73743. for (var i = 0; i < points.elements.length; i++) {
  73744. var p = points.elements[i];
  73745. var p1;
  73746. if ((i + 1) > points.elements.length - 1) {
  73747. p1 = points.elements[0];
  73748. }
  73749. else {
  73750. p1 = points.elements[i + 1];
  73751. }
  73752. positions.push(p.x, 0, p.y);
  73753. positions.push(p.x, -depth, p.y);
  73754. positions.push(p1.x, 0, p1.y);
  73755. positions.push(p1.x, -depth, p1.y);
  73756. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73757. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73758. var v3 = v2.subtract(v1);
  73759. var v4 = new BABYLON.Vector3(0, 1, 0);
  73760. var vn = BABYLON.Vector3.Cross(v3, v4);
  73761. vn = vn.normalize();
  73762. uvs.push(ulength / bounds.width, 0);
  73763. uvs.push(ulength / bounds.width, 1);
  73764. ulength += v3.length();
  73765. uvs.push((ulength / bounds.width), 0);
  73766. uvs.push((ulength / bounds.width), 1);
  73767. if (!flip) {
  73768. normals.push(-vn.x, -vn.y, -vn.z);
  73769. normals.push(-vn.x, -vn.y, -vn.z);
  73770. normals.push(-vn.x, -vn.y, -vn.z);
  73771. normals.push(-vn.x, -vn.y, -vn.z);
  73772. indices.push(StartIndex);
  73773. indices.push(StartIndex + 1);
  73774. indices.push(StartIndex + 2);
  73775. indices.push(StartIndex + 1);
  73776. indices.push(StartIndex + 3);
  73777. indices.push(StartIndex + 2);
  73778. }
  73779. else {
  73780. normals.push(vn.x, vn.y, vn.z);
  73781. normals.push(vn.x, vn.y, vn.z);
  73782. normals.push(vn.x, vn.y, vn.z);
  73783. normals.push(vn.x, vn.y, vn.z);
  73784. indices.push(StartIndex);
  73785. indices.push(StartIndex + 2);
  73786. indices.push(StartIndex + 1);
  73787. indices.push(StartIndex + 1);
  73788. indices.push(StartIndex + 2);
  73789. indices.push(StartIndex + 3);
  73790. }
  73791. StartIndex += 4;
  73792. }
  73793. ;
  73794. };
  73795. return PolygonMeshBuilder;
  73796. }());
  73797. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73798. })(BABYLON || (BABYLON = {}));
  73799. //# sourceMappingURL=babylon.polygonMesh.js.map
  73800. var BABYLON;
  73801. (function (BABYLON) {
  73802. // Unique ID when we import meshes from Babylon to CSG
  73803. var currentCSGMeshId = 0;
  73804. // # class Vertex
  73805. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73806. // one to provide additional features like texture coordinates and vertex
  73807. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73808. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73809. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73810. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73811. // is not used anywhere else.
  73812. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73813. var Vertex = /** @class */ (function () {
  73814. function Vertex(pos, normal, uv) {
  73815. this.pos = pos;
  73816. this.normal = normal;
  73817. this.uv = uv;
  73818. }
  73819. Vertex.prototype.clone = function () {
  73820. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73821. };
  73822. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73823. // orientation of a polygon is flipped.
  73824. Vertex.prototype.flip = function () {
  73825. this.normal = this.normal.scale(-1);
  73826. };
  73827. // Create a new vertex between this vertex and `other` by linearly
  73828. // interpolating all properties using a parameter of `t`. Subclasses should
  73829. // override this to interpolate additional properties.
  73830. Vertex.prototype.interpolate = function (other, t) {
  73831. 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));
  73832. };
  73833. return Vertex;
  73834. }());
  73835. // # class Plane
  73836. // Represents a plane in 3D space.
  73837. var Plane = /** @class */ (function () {
  73838. function Plane(normal, w) {
  73839. this.normal = normal;
  73840. this.w = w;
  73841. }
  73842. Plane.FromPoints = function (a, b, c) {
  73843. var v0 = c.subtract(a);
  73844. var v1 = b.subtract(a);
  73845. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73846. return null;
  73847. }
  73848. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73849. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73850. };
  73851. Plane.prototype.clone = function () {
  73852. return new Plane(this.normal.clone(), this.w);
  73853. };
  73854. Plane.prototype.flip = function () {
  73855. this.normal.scaleInPlace(-1);
  73856. this.w = -this.w;
  73857. };
  73858. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73859. // fragments in the appropriate lists. Coplanar polygons go into either
  73860. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73861. // respect to this plane. Polygons in front or in back of this plane go into
  73862. // either `front` or `back`.
  73863. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73864. var COPLANAR = 0;
  73865. var FRONT = 1;
  73866. var BACK = 2;
  73867. var SPANNING = 3;
  73868. // Classify each point as well as the entire polygon into one of the above
  73869. // four classes.
  73870. var polygonType = 0;
  73871. var types = [];
  73872. var i;
  73873. var t;
  73874. for (i = 0; i < polygon.vertices.length; i++) {
  73875. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73876. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73877. polygonType |= type;
  73878. types.push(type);
  73879. }
  73880. // Put the polygon in the correct list, splitting it when necessary.
  73881. switch (polygonType) {
  73882. case COPLANAR:
  73883. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73884. break;
  73885. case FRONT:
  73886. front.push(polygon);
  73887. break;
  73888. case BACK:
  73889. back.push(polygon);
  73890. break;
  73891. case SPANNING:
  73892. var f = [], b = [];
  73893. for (i = 0; i < polygon.vertices.length; i++) {
  73894. var j = (i + 1) % polygon.vertices.length;
  73895. var ti = types[i], tj = types[j];
  73896. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73897. if (ti !== BACK)
  73898. f.push(vi);
  73899. if (ti !== FRONT)
  73900. b.push(ti !== BACK ? vi.clone() : vi);
  73901. if ((ti | tj) === SPANNING) {
  73902. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73903. var v = vi.interpolate(vj, t);
  73904. f.push(v);
  73905. b.push(v.clone());
  73906. }
  73907. }
  73908. var poly;
  73909. if (f.length >= 3) {
  73910. poly = new Polygon(f, polygon.shared);
  73911. if (poly.plane)
  73912. front.push(poly);
  73913. }
  73914. if (b.length >= 3) {
  73915. poly = new Polygon(b, polygon.shared);
  73916. if (poly.plane)
  73917. back.push(poly);
  73918. }
  73919. break;
  73920. }
  73921. };
  73922. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73923. // point is on the plane.
  73924. Plane.EPSILON = 1e-5;
  73925. return Plane;
  73926. }());
  73927. // # class Polygon
  73928. // Represents a convex polygon. The vertices used to initialize a polygon must
  73929. // be coplanar and form a convex loop.
  73930. //
  73931. // Each convex polygon has a `shared` property, which is shared between all
  73932. // polygons that are clones of each other or were split from the same polygon.
  73933. // This can be used to define per-polygon properties (such as surface color).
  73934. var Polygon = /** @class */ (function () {
  73935. function Polygon(vertices, shared) {
  73936. this.vertices = vertices;
  73937. this.shared = shared;
  73938. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73939. }
  73940. Polygon.prototype.clone = function () {
  73941. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73942. return new Polygon(vertices, this.shared);
  73943. };
  73944. Polygon.prototype.flip = function () {
  73945. this.vertices.reverse().map(function (v) { v.flip(); });
  73946. this.plane.flip();
  73947. };
  73948. return Polygon;
  73949. }());
  73950. // # class Node
  73951. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73952. // by picking a polygon to split along. That polygon (and all other coplanar
  73953. // polygons) are added directly to that node and the other polygons are added to
  73954. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73955. // no distinction between internal and leaf nodes.
  73956. var Node = /** @class */ (function () {
  73957. function Node(polygons) {
  73958. this.plane = null;
  73959. this.front = null;
  73960. this.back = null;
  73961. this.polygons = new Array();
  73962. if (polygons) {
  73963. this.build(polygons);
  73964. }
  73965. }
  73966. Node.prototype.clone = function () {
  73967. var node = new Node();
  73968. node.plane = this.plane && this.plane.clone();
  73969. node.front = this.front && this.front.clone();
  73970. node.back = this.back && this.back.clone();
  73971. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73972. return node;
  73973. };
  73974. // Convert solid space to empty space and empty space to solid space.
  73975. Node.prototype.invert = function () {
  73976. for (var i = 0; i < this.polygons.length; i++) {
  73977. this.polygons[i].flip();
  73978. }
  73979. if (this.plane) {
  73980. this.plane.flip();
  73981. }
  73982. if (this.front) {
  73983. this.front.invert();
  73984. }
  73985. if (this.back) {
  73986. this.back.invert();
  73987. }
  73988. var temp = this.front;
  73989. this.front = this.back;
  73990. this.back = temp;
  73991. };
  73992. // Recursively remove all polygons in `polygons` that are inside this BSP
  73993. // tree.
  73994. Node.prototype.clipPolygons = function (polygons) {
  73995. if (!this.plane)
  73996. return polygons.slice();
  73997. var front = new Array(), back = new Array();
  73998. for (var i = 0; i < polygons.length; i++) {
  73999. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74000. }
  74001. if (this.front) {
  74002. front = this.front.clipPolygons(front);
  74003. }
  74004. if (this.back) {
  74005. back = this.back.clipPolygons(back);
  74006. }
  74007. else {
  74008. back = [];
  74009. }
  74010. return front.concat(back);
  74011. };
  74012. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74013. // `bsp`.
  74014. Node.prototype.clipTo = function (bsp) {
  74015. this.polygons = bsp.clipPolygons(this.polygons);
  74016. if (this.front)
  74017. this.front.clipTo(bsp);
  74018. if (this.back)
  74019. this.back.clipTo(bsp);
  74020. };
  74021. // Return a list of all polygons in this BSP tree.
  74022. Node.prototype.allPolygons = function () {
  74023. var polygons = this.polygons.slice();
  74024. if (this.front)
  74025. polygons = polygons.concat(this.front.allPolygons());
  74026. if (this.back)
  74027. polygons = polygons.concat(this.back.allPolygons());
  74028. return polygons;
  74029. };
  74030. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74031. // new polygons are filtered down to the bottom of the tree and become new
  74032. // nodes there. Each set of polygons is partitioned using the first polygon
  74033. // (no heuristic is used to pick a good split).
  74034. Node.prototype.build = function (polygons) {
  74035. if (!polygons.length)
  74036. return;
  74037. if (!this.plane)
  74038. this.plane = polygons[0].plane.clone();
  74039. var front = new Array(), back = new Array();
  74040. for (var i = 0; i < polygons.length; i++) {
  74041. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74042. }
  74043. if (front.length) {
  74044. if (!this.front)
  74045. this.front = new Node();
  74046. this.front.build(front);
  74047. }
  74048. if (back.length) {
  74049. if (!this.back)
  74050. this.back = new Node();
  74051. this.back.build(back);
  74052. }
  74053. };
  74054. return Node;
  74055. }());
  74056. var CSG = /** @class */ (function () {
  74057. function CSG() {
  74058. this.polygons = new Array();
  74059. }
  74060. // Convert BABYLON.Mesh to BABYLON.CSG
  74061. CSG.FromMesh = function (mesh) {
  74062. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74063. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74064. if (mesh instanceof BABYLON.Mesh) {
  74065. mesh.computeWorldMatrix(true);
  74066. matrix = mesh.getWorldMatrix();
  74067. meshPosition = mesh.position.clone();
  74068. meshRotation = mesh.rotation.clone();
  74069. if (mesh.rotationQuaternion) {
  74070. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74071. }
  74072. meshScaling = mesh.scaling.clone();
  74073. }
  74074. else {
  74075. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74076. }
  74077. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74078. var subMeshes = mesh.subMeshes;
  74079. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74080. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74081. vertices = [];
  74082. for (var j = 0; j < 3; j++) {
  74083. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74084. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74085. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74086. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74087. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74088. vertex = new Vertex(position, normal, uv);
  74089. vertices.push(vertex);
  74090. }
  74091. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74092. // To handle the case of degenerated triangle
  74093. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74094. if (polygon.plane)
  74095. polygons.push(polygon);
  74096. }
  74097. }
  74098. var csg = CSG.FromPolygons(polygons);
  74099. csg.matrix = matrix;
  74100. csg.position = meshPosition;
  74101. csg.rotation = meshRotation;
  74102. csg.scaling = meshScaling;
  74103. csg.rotationQuaternion = meshRotationQuaternion;
  74104. currentCSGMeshId++;
  74105. return csg;
  74106. };
  74107. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74108. CSG.FromPolygons = function (polygons) {
  74109. var csg = new CSG();
  74110. csg.polygons = polygons;
  74111. return csg;
  74112. };
  74113. CSG.prototype.clone = function () {
  74114. var csg = new CSG();
  74115. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74116. csg.copyTransformAttributes(this);
  74117. return csg;
  74118. };
  74119. CSG.prototype.union = function (csg) {
  74120. var a = new Node(this.clone().polygons);
  74121. var b = new Node(csg.clone().polygons);
  74122. a.clipTo(b);
  74123. b.clipTo(a);
  74124. b.invert();
  74125. b.clipTo(a);
  74126. b.invert();
  74127. a.build(b.allPolygons());
  74128. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74129. };
  74130. CSG.prototype.unionInPlace = function (csg) {
  74131. var a = new Node(this.polygons);
  74132. var b = new Node(csg.polygons);
  74133. a.clipTo(b);
  74134. b.clipTo(a);
  74135. b.invert();
  74136. b.clipTo(a);
  74137. b.invert();
  74138. a.build(b.allPolygons());
  74139. this.polygons = a.allPolygons();
  74140. };
  74141. CSG.prototype.subtract = function (csg) {
  74142. var a = new Node(this.clone().polygons);
  74143. var b = new Node(csg.clone().polygons);
  74144. a.invert();
  74145. a.clipTo(b);
  74146. b.clipTo(a);
  74147. b.invert();
  74148. b.clipTo(a);
  74149. b.invert();
  74150. a.build(b.allPolygons());
  74151. a.invert();
  74152. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74153. };
  74154. CSG.prototype.subtractInPlace = function (csg) {
  74155. var a = new Node(this.polygons);
  74156. var b = new Node(csg.polygons);
  74157. a.invert();
  74158. a.clipTo(b);
  74159. b.clipTo(a);
  74160. b.invert();
  74161. b.clipTo(a);
  74162. b.invert();
  74163. a.build(b.allPolygons());
  74164. a.invert();
  74165. this.polygons = a.allPolygons();
  74166. };
  74167. CSG.prototype.intersect = function (csg) {
  74168. var a = new Node(this.clone().polygons);
  74169. var b = new Node(csg.clone().polygons);
  74170. a.invert();
  74171. b.clipTo(a);
  74172. b.invert();
  74173. a.clipTo(b);
  74174. b.clipTo(a);
  74175. a.build(b.allPolygons());
  74176. a.invert();
  74177. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74178. };
  74179. CSG.prototype.intersectInPlace = function (csg) {
  74180. var a = new Node(this.polygons);
  74181. var b = new Node(csg.polygons);
  74182. a.invert();
  74183. b.clipTo(a);
  74184. b.invert();
  74185. a.clipTo(b);
  74186. b.clipTo(a);
  74187. a.build(b.allPolygons());
  74188. a.invert();
  74189. this.polygons = a.allPolygons();
  74190. };
  74191. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74192. // not modified.
  74193. CSG.prototype.inverse = function () {
  74194. var csg = this.clone();
  74195. csg.inverseInPlace();
  74196. return csg;
  74197. };
  74198. CSG.prototype.inverseInPlace = function () {
  74199. this.polygons.map(function (p) { p.flip(); });
  74200. };
  74201. // This is used to keep meshes transformations so they can be restored
  74202. // when we build back a Babylon Mesh
  74203. // NB : All CSG operations are performed in world coordinates
  74204. CSG.prototype.copyTransformAttributes = function (csg) {
  74205. this.matrix = csg.matrix;
  74206. this.position = csg.position;
  74207. this.rotation = csg.rotation;
  74208. this.scaling = csg.scaling;
  74209. this.rotationQuaternion = csg.rotationQuaternion;
  74210. return this;
  74211. };
  74212. // Build Raw mesh from CSG
  74213. // Coordinates here are in world space
  74214. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74215. var matrix = this.matrix.clone();
  74216. matrix.invert();
  74217. 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;
  74218. if (keepSubMeshes) {
  74219. // Sort Polygons, since subMeshes are indices range
  74220. polygons.sort(function (a, b) {
  74221. if (a.shared.meshId === b.shared.meshId) {
  74222. return a.shared.subMeshId - b.shared.subMeshId;
  74223. }
  74224. else {
  74225. return a.shared.meshId - b.shared.meshId;
  74226. }
  74227. });
  74228. }
  74229. for (var i = 0, il = polygons.length; i < il; i++) {
  74230. polygon = polygons[i];
  74231. // Building SubMeshes
  74232. if (!subMesh_dict[polygon.shared.meshId]) {
  74233. subMesh_dict[polygon.shared.meshId] = {};
  74234. }
  74235. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74236. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74237. indexStart: +Infinity,
  74238. indexEnd: -Infinity,
  74239. materialIndex: polygon.shared.materialIndex
  74240. };
  74241. }
  74242. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74243. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74244. polygonIndices[0] = 0;
  74245. polygonIndices[1] = j - 1;
  74246. polygonIndices[2] = j;
  74247. for (var k = 0; k < 3; k++) {
  74248. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74249. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74250. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74251. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74252. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74253. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74254. // Check if 2 points can be merged
  74255. if (!(typeof vertex_idx !== 'undefined' &&
  74256. normals[vertex_idx * 3] === localNormal.x &&
  74257. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74258. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74259. uvs[vertex_idx * 2] === uv.x &&
  74260. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74261. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74262. uvs.push(uv.x, uv.y);
  74263. normals.push(normal.x, normal.y, normal.z);
  74264. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74265. }
  74266. indices.push(vertex_idx);
  74267. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74268. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74269. currentIndex++;
  74270. }
  74271. }
  74272. }
  74273. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74274. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74275. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74276. mesh.setIndices(indices, null);
  74277. if (keepSubMeshes) {
  74278. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74279. var materialIndexOffset = 0, materialMaxIndex;
  74280. mesh.subMeshes = new Array();
  74281. for (var m in subMesh_dict) {
  74282. materialMaxIndex = -1;
  74283. for (var sm in subMesh_dict[m]) {
  74284. subMesh_obj = subMesh_dict[m][sm];
  74285. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74286. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74287. }
  74288. materialIndexOffset += ++materialMaxIndex;
  74289. }
  74290. }
  74291. return mesh;
  74292. };
  74293. // Build Mesh from CSG taking material and transforms into account
  74294. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74295. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74296. mesh.material = material;
  74297. mesh.position.copyFrom(this.position);
  74298. mesh.rotation.copyFrom(this.rotation);
  74299. if (this.rotationQuaternion) {
  74300. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74301. }
  74302. mesh.scaling.copyFrom(this.scaling);
  74303. mesh.computeWorldMatrix(true);
  74304. return mesh;
  74305. };
  74306. return CSG;
  74307. }());
  74308. BABYLON.CSG = CSG;
  74309. })(BABYLON || (BABYLON = {}));
  74310. //# sourceMappingURL=babylon.csg.js.map
  74311. var BABYLON;
  74312. (function (BABYLON) {
  74313. var LensFlare = /** @class */ (function () {
  74314. function LensFlare(size, position, color, imgUrl, system) {
  74315. this.size = size;
  74316. this.position = position;
  74317. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74318. this.color = color || new BABYLON.Color3(1, 1, 1);
  74319. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74320. this._system = system;
  74321. system.lensFlares.push(this);
  74322. }
  74323. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74324. return new LensFlare(size, position, color, imgUrl, system);
  74325. };
  74326. LensFlare.prototype.dispose = function () {
  74327. if (this.texture) {
  74328. this.texture.dispose();
  74329. }
  74330. // Remove from scene
  74331. var index = this._system.lensFlares.indexOf(this);
  74332. this._system.lensFlares.splice(index, 1);
  74333. };
  74334. ;
  74335. return LensFlare;
  74336. }());
  74337. BABYLON.LensFlare = LensFlare;
  74338. })(BABYLON || (BABYLON = {}));
  74339. //# sourceMappingURL=babylon.lensFlare.js.map
  74340. var BABYLON;
  74341. (function (BABYLON) {
  74342. var LensFlareSystem = /** @class */ (function () {
  74343. function LensFlareSystem(name, emitter, scene) {
  74344. this.name = name;
  74345. this.lensFlares = new Array();
  74346. this.borderLimit = 300;
  74347. this.viewportBorder = 0;
  74348. this.layerMask = 0x0FFFFFFF;
  74349. this._vertexBuffers = {};
  74350. this._isEnabled = true;
  74351. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74352. this._emitter = emitter;
  74353. this.id = name;
  74354. scene.lensFlareSystems.push(this);
  74355. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74356. var engine = scene.getEngine();
  74357. // VBO
  74358. var vertices = [];
  74359. vertices.push(1, 1);
  74360. vertices.push(-1, 1);
  74361. vertices.push(-1, -1);
  74362. vertices.push(1, -1);
  74363. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74364. // Indices
  74365. var indices = [];
  74366. indices.push(0);
  74367. indices.push(1);
  74368. indices.push(2);
  74369. indices.push(0);
  74370. indices.push(2);
  74371. indices.push(3);
  74372. this._indexBuffer = engine.createIndexBuffer(indices);
  74373. // Effects
  74374. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74375. }
  74376. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74377. get: function () {
  74378. return this._isEnabled;
  74379. },
  74380. set: function (value) {
  74381. this._isEnabled = value;
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. LensFlareSystem.prototype.getScene = function () {
  74387. return this._scene;
  74388. };
  74389. LensFlareSystem.prototype.getEmitter = function () {
  74390. return this._emitter;
  74391. };
  74392. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74393. this._emitter = newEmitter;
  74394. };
  74395. LensFlareSystem.prototype.getEmitterPosition = function () {
  74396. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74397. };
  74398. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74399. var position = this.getEmitterPosition();
  74400. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74401. this._positionX = position.x;
  74402. this._positionY = position.y;
  74403. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74404. if (this.viewportBorder > 0) {
  74405. globalViewport.x -= this.viewportBorder;
  74406. globalViewport.y -= this.viewportBorder;
  74407. globalViewport.width += this.viewportBorder * 2;
  74408. globalViewport.height += this.viewportBorder * 2;
  74409. position.x += this.viewportBorder;
  74410. position.y += this.viewportBorder;
  74411. this._positionX += this.viewportBorder;
  74412. this._positionY += this.viewportBorder;
  74413. }
  74414. if (position.z > 0) {
  74415. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74416. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74417. return true;
  74418. }
  74419. return true;
  74420. }
  74421. return false;
  74422. };
  74423. LensFlareSystem.prototype._isVisible = function () {
  74424. if (!this._isEnabled || !this._scene.activeCamera) {
  74425. return false;
  74426. }
  74427. var emitterPosition = this.getEmitterPosition();
  74428. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74429. var distance = direction.length();
  74430. direction.normalize();
  74431. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74432. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74433. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74434. };
  74435. LensFlareSystem.prototype.render = function () {
  74436. if (!this._effect.isReady() || !this._scene.activeCamera)
  74437. return false;
  74438. var engine = this._scene.getEngine();
  74439. var viewport = this._scene.activeCamera.viewport;
  74440. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74441. // Position
  74442. if (!this.computeEffectivePosition(globalViewport)) {
  74443. return false;
  74444. }
  74445. // Visibility
  74446. if (!this._isVisible()) {
  74447. return false;
  74448. }
  74449. // Intensity
  74450. var awayX;
  74451. var awayY;
  74452. if (this._positionX < this.borderLimit + globalViewport.x) {
  74453. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74454. }
  74455. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74456. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74457. }
  74458. else {
  74459. awayX = 0;
  74460. }
  74461. if (this._positionY < this.borderLimit + globalViewport.y) {
  74462. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74463. }
  74464. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74465. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74466. }
  74467. else {
  74468. awayY = 0;
  74469. }
  74470. var away = (awayX > awayY) ? awayX : awayY;
  74471. away -= this.viewportBorder;
  74472. if (away > this.borderLimit) {
  74473. away = this.borderLimit;
  74474. }
  74475. var intensity = 1.0 - (away / this.borderLimit);
  74476. if (intensity < 0) {
  74477. return false;
  74478. }
  74479. if (intensity > 1.0) {
  74480. intensity = 1.0;
  74481. }
  74482. if (this.viewportBorder > 0) {
  74483. globalViewport.x += this.viewportBorder;
  74484. globalViewport.y += this.viewportBorder;
  74485. globalViewport.width -= this.viewportBorder * 2;
  74486. globalViewport.height -= this.viewportBorder * 2;
  74487. this._positionX -= this.viewportBorder;
  74488. this._positionY -= this.viewportBorder;
  74489. }
  74490. // Position
  74491. var centerX = globalViewport.x + globalViewport.width / 2;
  74492. var centerY = globalViewport.y + globalViewport.height / 2;
  74493. var distX = centerX - this._positionX;
  74494. var distY = centerY - this._positionY;
  74495. // Effects
  74496. engine.enableEffect(this._effect);
  74497. engine.setState(false);
  74498. engine.setDepthBuffer(false);
  74499. // VBOs
  74500. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74501. // Flares
  74502. for (var index = 0; index < this.lensFlares.length; index++) {
  74503. var flare = this.lensFlares[index];
  74504. engine.setAlphaMode(flare.alphaMode);
  74505. var x = centerX - (distX * flare.position);
  74506. var y = centerY - (distY * flare.position);
  74507. var cw = flare.size;
  74508. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74509. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74510. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74511. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74512. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74513. // Texture
  74514. this._effect.setTexture("textureSampler", flare.texture);
  74515. // Color
  74516. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74517. // Draw order
  74518. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74519. }
  74520. engine.setDepthBuffer(true);
  74521. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74522. return true;
  74523. };
  74524. LensFlareSystem.prototype.dispose = function () {
  74525. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74526. if (vertexBuffer) {
  74527. vertexBuffer.dispose();
  74528. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74529. }
  74530. if (this._indexBuffer) {
  74531. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74532. this._indexBuffer = null;
  74533. }
  74534. while (this.lensFlares.length) {
  74535. this.lensFlares[0].dispose();
  74536. }
  74537. // Remove from scene
  74538. var index = this._scene.lensFlareSystems.indexOf(this);
  74539. this._scene.lensFlareSystems.splice(index, 1);
  74540. };
  74541. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74542. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74543. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74544. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74545. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74546. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74547. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74548. var parsedFlare = parsedLensFlareSystem.flares[index];
  74549. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74550. }
  74551. return lensFlareSystem;
  74552. };
  74553. LensFlareSystem.prototype.serialize = function () {
  74554. var serializationObject = {};
  74555. serializationObject.id = this.id;
  74556. serializationObject.name = this.name;
  74557. serializationObject.emitterId = this.getEmitter().id;
  74558. serializationObject.borderLimit = this.borderLimit;
  74559. serializationObject.flares = [];
  74560. for (var index = 0; index < this.lensFlares.length; index++) {
  74561. var flare = this.lensFlares[index];
  74562. serializationObject.flares.push({
  74563. size: flare.size,
  74564. position: flare.position,
  74565. color: flare.color.asArray(),
  74566. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74567. });
  74568. }
  74569. return serializationObject;
  74570. };
  74571. return LensFlareSystem;
  74572. }());
  74573. BABYLON.LensFlareSystem = LensFlareSystem;
  74574. })(BABYLON || (BABYLON = {}));
  74575. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74576. var BABYLON;
  74577. (function (BABYLON) {
  74578. /**
  74579. * This is a holder class for the physics joint created by the physics plugin.
  74580. * It holds a set of functions to control the underlying joint.
  74581. */
  74582. var PhysicsJoint = /** @class */ (function () {
  74583. function PhysicsJoint(type, jointData) {
  74584. this.type = type;
  74585. this.jointData = jointData;
  74586. jointData.nativeParams = jointData.nativeParams || {};
  74587. }
  74588. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74589. get: function () {
  74590. return this._physicsJoint;
  74591. },
  74592. set: function (newJoint) {
  74593. if (this._physicsJoint) {
  74594. //remove from the wolrd
  74595. }
  74596. this._physicsJoint = newJoint;
  74597. },
  74598. enumerable: true,
  74599. configurable: true
  74600. });
  74601. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74602. set: function (physicsPlugin) {
  74603. this._physicsPlugin = physicsPlugin;
  74604. },
  74605. enumerable: true,
  74606. configurable: true
  74607. });
  74608. /**
  74609. * Execute a function that is physics-plugin specific.
  74610. * @param {Function} func the function that will be executed.
  74611. * It accepts two parameters: the physics world and the physics joint.
  74612. */
  74613. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74614. func(this._physicsPlugin.world, this._physicsJoint);
  74615. };
  74616. //TODO check if the native joints are the same
  74617. //Joint Types
  74618. PhysicsJoint.DistanceJoint = 0;
  74619. PhysicsJoint.HingeJoint = 1;
  74620. PhysicsJoint.BallAndSocketJoint = 2;
  74621. PhysicsJoint.WheelJoint = 3;
  74622. PhysicsJoint.SliderJoint = 4;
  74623. //OIMO
  74624. PhysicsJoint.PrismaticJoint = 5;
  74625. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74626. PhysicsJoint.UniversalJoint = 6;
  74627. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74628. //Cannon
  74629. //Similar to a Ball-Joint. Different in params
  74630. PhysicsJoint.PointToPointJoint = 8;
  74631. //Cannon only at the moment
  74632. PhysicsJoint.SpringJoint = 9;
  74633. PhysicsJoint.LockJoint = 10;
  74634. return PhysicsJoint;
  74635. }());
  74636. BABYLON.PhysicsJoint = PhysicsJoint;
  74637. /**
  74638. * A class representing a physics distance joint.
  74639. */
  74640. var DistanceJoint = /** @class */ (function (_super) {
  74641. __extends(DistanceJoint, _super);
  74642. function DistanceJoint(jointData) {
  74643. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74644. }
  74645. /**
  74646. * Update the predefined distance.
  74647. */
  74648. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74649. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74650. };
  74651. return DistanceJoint;
  74652. }(PhysicsJoint));
  74653. BABYLON.DistanceJoint = DistanceJoint;
  74654. var MotorEnabledJoint = /** @class */ (function (_super) {
  74655. __extends(MotorEnabledJoint, _super);
  74656. function MotorEnabledJoint(type, jointData) {
  74657. return _super.call(this, type, jointData) || this;
  74658. }
  74659. /**
  74660. * Set the motor values.
  74661. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74662. * @param {number} force the force to apply
  74663. * @param {number} maxForce max force for this motor.
  74664. */
  74665. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74666. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74667. };
  74668. /**
  74669. * Set the motor's limits.
  74670. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74671. */
  74672. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74673. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74674. };
  74675. return MotorEnabledJoint;
  74676. }(PhysicsJoint));
  74677. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74678. /**
  74679. * This class represents a single hinge physics joint
  74680. */
  74681. var HingeJoint = /** @class */ (function (_super) {
  74682. __extends(HingeJoint, _super);
  74683. function HingeJoint(jointData) {
  74684. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74685. }
  74686. /**
  74687. * Set the motor values.
  74688. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74689. * @param {number} force the force to apply
  74690. * @param {number} maxForce max force for this motor.
  74691. */
  74692. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74693. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74694. };
  74695. /**
  74696. * Set the motor's limits.
  74697. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74698. */
  74699. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74700. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74701. };
  74702. return HingeJoint;
  74703. }(MotorEnabledJoint));
  74704. BABYLON.HingeJoint = HingeJoint;
  74705. /**
  74706. * This class represents a dual hinge physics joint (same as wheel joint)
  74707. */
  74708. var Hinge2Joint = /** @class */ (function (_super) {
  74709. __extends(Hinge2Joint, _super);
  74710. function Hinge2Joint(jointData) {
  74711. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74712. }
  74713. /**
  74714. * Set the motor values.
  74715. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74716. * @param {number} force the force to apply
  74717. * @param {number} maxForce max force for this motor.
  74718. * @param {motorIndex} the motor's index, 0 or 1.
  74719. */
  74720. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74721. if (motorIndex === void 0) { motorIndex = 0; }
  74722. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74723. };
  74724. /**
  74725. * Set the motor limits.
  74726. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74727. * @param {number} upperLimit the upper limit
  74728. * @param {number} lowerLimit lower limit
  74729. * @param {motorIndex} the motor's index, 0 or 1.
  74730. */
  74731. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74732. if (motorIndex === void 0) { motorIndex = 0; }
  74733. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74734. };
  74735. return Hinge2Joint;
  74736. }(MotorEnabledJoint));
  74737. BABYLON.Hinge2Joint = Hinge2Joint;
  74738. })(BABYLON || (BABYLON = {}));
  74739. //# sourceMappingURL=babylon.physicsJoint.js.map
  74740. var BABYLON;
  74741. (function (BABYLON) {
  74742. var PhysicsImpostor = /** @class */ (function () {
  74743. function PhysicsImpostor(object, type, _options, _scene) {
  74744. if (_options === void 0) { _options = { mass: 0 }; }
  74745. var _this = this;
  74746. this.object = object;
  74747. this.type = type;
  74748. this._options = _options;
  74749. this._scene = _scene;
  74750. this._bodyUpdateRequired = false;
  74751. this._onBeforePhysicsStepCallbacks = new Array();
  74752. this._onAfterPhysicsStepCallbacks = new Array();
  74753. this._onPhysicsCollideCallbacks = [];
  74754. this._deltaPosition = BABYLON.Vector3.Zero();
  74755. this._isDisposed = false;
  74756. //temp variables for parent rotation calculations
  74757. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74758. this._tmpQuat = new BABYLON.Quaternion();
  74759. this._tmpQuat2 = new BABYLON.Quaternion();
  74760. /**
  74761. * this function is executed by the physics engine.
  74762. */
  74763. this.beforeStep = function () {
  74764. if (!_this._physicsEngine) {
  74765. return;
  74766. }
  74767. _this.object.translate(_this._deltaPosition, -1);
  74768. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74769. _this.object.computeWorldMatrix(false);
  74770. if (_this.object.parent && _this.object.rotationQuaternion) {
  74771. _this.getParentsRotation();
  74772. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74773. }
  74774. else {
  74775. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74776. }
  74777. if (!_this._options.disableBidirectionalTransformation) {
  74778. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74779. }
  74780. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74781. func(_this);
  74782. });
  74783. };
  74784. /**
  74785. * this function is executed by the physics engine.
  74786. */
  74787. this.afterStep = function () {
  74788. if (!_this._physicsEngine) {
  74789. return;
  74790. }
  74791. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74792. func(_this);
  74793. });
  74794. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74795. // object has now its world rotation. needs to be converted to local.
  74796. if (_this.object.parent && _this.object.rotationQuaternion) {
  74797. _this.getParentsRotation();
  74798. _this._tmpQuat.conjugateInPlace();
  74799. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74800. }
  74801. // take the position set and make it the absolute position of this object.
  74802. _this.object.setAbsolutePosition(_this.object.position);
  74803. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74804. _this.object.translate(_this._deltaPosition, 1);
  74805. };
  74806. /**
  74807. * Legacy collision detection event support
  74808. */
  74809. this.onCollideEvent = null;
  74810. //event and body object due to cannon's event-based architecture.
  74811. this.onCollide = function (e) {
  74812. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74813. return;
  74814. }
  74815. if (!_this._physicsEngine) {
  74816. return;
  74817. }
  74818. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74819. if (otherImpostor) {
  74820. // Legacy collision detection event support
  74821. if (_this.onCollideEvent) {
  74822. _this.onCollideEvent(_this, otherImpostor);
  74823. }
  74824. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74825. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74826. }).forEach(function (obj) {
  74827. obj.callback(_this, otherImpostor);
  74828. });
  74829. }
  74830. };
  74831. //sanity check!
  74832. if (!this.object) {
  74833. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74834. return;
  74835. }
  74836. //legacy support for old syntax.
  74837. if (!this._scene && object.getScene) {
  74838. this._scene = object.getScene();
  74839. }
  74840. if (!this._scene) {
  74841. return;
  74842. }
  74843. this._physicsEngine = this._scene.getPhysicsEngine();
  74844. if (!this._physicsEngine) {
  74845. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74846. }
  74847. else {
  74848. //set the object's quaternion, if not set
  74849. if (!this.object.rotationQuaternion) {
  74850. if (this.object.rotation) {
  74851. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74852. }
  74853. else {
  74854. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74855. }
  74856. }
  74857. //default options params
  74858. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74859. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74860. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74861. this._joints = [];
  74862. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74863. if (!this.object.parent || this._options.ignoreParent) {
  74864. this._init();
  74865. }
  74866. else if (this.object.parent.physicsImpostor) {
  74867. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74868. }
  74869. }
  74870. }
  74871. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74872. get: function () {
  74873. return this._isDisposed;
  74874. },
  74875. enumerable: true,
  74876. configurable: true
  74877. });
  74878. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74879. get: function () {
  74880. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74881. },
  74882. set: function (value) {
  74883. this.setMass(value);
  74884. },
  74885. enumerable: true,
  74886. configurable: true
  74887. });
  74888. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74889. get: function () {
  74890. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74891. },
  74892. set: function (value) {
  74893. if (!this._physicsEngine) {
  74894. return;
  74895. }
  74896. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74897. },
  74898. enumerable: true,
  74899. configurable: true
  74900. });
  74901. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74902. get: function () {
  74903. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74904. },
  74905. set: function (value) {
  74906. if (!this._physicsEngine) {
  74907. return;
  74908. }
  74909. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74910. },
  74911. enumerable: true,
  74912. configurable: true
  74913. });
  74914. /**
  74915. * This function will completly initialize this impostor.
  74916. * It will create a new body - but only if this mesh has no parent.
  74917. * If it has, this impostor will not be used other than to define the impostor
  74918. * of the child mesh.
  74919. */
  74920. PhysicsImpostor.prototype._init = function () {
  74921. if (!this._physicsEngine) {
  74922. return;
  74923. }
  74924. this._physicsEngine.removeImpostor(this);
  74925. this.physicsBody = null;
  74926. this._parent = this._parent || this._getPhysicsParent();
  74927. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74928. this._physicsEngine.addImpostor(this);
  74929. }
  74930. };
  74931. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74932. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74933. var parentMesh = this.object.parent;
  74934. return parentMesh.physicsImpostor;
  74935. }
  74936. return null;
  74937. };
  74938. /**
  74939. * Should a new body be generated.
  74940. */
  74941. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74942. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74943. };
  74944. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74945. this.forceUpdate();
  74946. };
  74947. /**
  74948. * Force a regeneration of this or the parent's impostor's body.
  74949. * Use under cautious - This will remove all joints already implemented.
  74950. */
  74951. PhysicsImpostor.prototype.forceUpdate = function () {
  74952. this._init();
  74953. if (this.parent && !this._options.ignoreParent) {
  74954. this.parent.forceUpdate();
  74955. }
  74956. };
  74957. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74958. /*public get mesh(): AbstractMesh {
  74959. return this._mesh;
  74960. }*/
  74961. /**
  74962. * Gets the body that holds this impostor. Either its own, or its parent.
  74963. */
  74964. get: function () {
  74965. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74966. },
  74967. /**
  74968. * Set the physics body. Used mainly by the physics engine/plugin
  74969. */
  74970. set: function (physicsBody) {
  74971. if (this._physicsBody && this._physicsEngine) {
  74972. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74973. }
  74974. this._physicsBody = physicsBody;
  74975. this.resetUpdateFlags();
  74976. },
  74977. enumerable: true,
  74978. configurable: true
  74979. });
  74980. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74981. get: function () {
  74982. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74983. },
  74984. set: function (value) {
  74985. this._parent = value;
  74986. },
  74987. enumerable: true,
  74988. configurable: true
  74989. });
  74990. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74991. this._bodyUpdateRequired = false;
  74992. };
  74993. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74994. if (this.object.getBoundingInfo) {
  74995. var q = this.object.rotationQuaternion;
  74996. //reset rotation
  74997. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74998. //calculate the world matrix with no rotation
  74999. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75000. var boundingInfo = this.object.getBoundingInfo();
  75001. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75002. //bring back the rotation
  75003. this.object.rotationQuaternion = q;
  75004. //calculate the world matrix with the new rotation
  75005. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75006. return size;
  75007. }
  75008. else {
  75009. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75010. }
  75011. };
  75012. PhysicsImpostor.prototype.getObjectCenter = function () {
  75013. if (this.object.getBoundingInfo) {
  75014. var boundingInfo = this.object.getBoundingInfo();
  75015. return boundingInfo.boundingBox.centerWorld;
  75016. }
  75017. else {
  75018. return this.object.position;
  75019. }
  75020. };
  75021. /**
  75022. * Get a specific parametes from the options parameter.
  75023. */
  75024. PhysicsImpostor.prototype.getParam = function (paramName) {
  75025. return this._options[paramName];
  75026. };
  75027. /**
  75028. * Sets a specific parameter in the options given to the physics plugin
  75029. */
  75030. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75031. this._options[paramName] = value;
  75032. this._bodyUpdateRequired = true;
  75033. };
  75034. /**
  75035. * Specifically change the body's mass option. Won't recreate the physics body object
  75036. */
  75037. PhysicsImpostor.prototype.setMass = function (mass) {
  75038. if (this.getParam("mass") !== mass) {
  75039. this.setParam("mass", mass);
  75040. }
  75041. if (this._physicsEngine) {
  75042. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75043. }
  75044. };
  75045. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75046. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75047. };
  75048. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75049. if (this._physicsEngine) {
  75050. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75051. }
  75052. };
  75053. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75054. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75055. };
  75056. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75057. if (this._physicsEngine) {
  75058. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75059. }
  75060. };
  75061. /**
  75062. * Execute a function with the physics plugin native code.
  75063. * Provide a function the will have two variables - the world object and the physics body object.
  75064. */
  75065. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75066. if (this._physicsEngine) {
  75067. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75068. }
  75069. };
  75070. /**
  75071. * Register a function that will be executed before the physics world is stepping forward.
  75072. */
  75073. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75074. this._onBeforePhysicsStepCallbacks.push(func);
  75075. };
  75076. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75077. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75078. if (index > -1) {
  75079. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75080. }
  75081. else {
  75082. BABYLON.Tools.Warn("Function to remove was not found");
  75083. }
  75084. };
  75085. /**
  75086. * Register a function that will be executed after the physics step
  75087. */
  75088. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75089. this._onAfterPhysicsStepCallbacks.push(func);
  75090. };
  75091. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75092. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75093. if (index > -1) {
  75094. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75095. }
  75096. else {
  75097. BABYLON.Tools.Warn("Function to remove was not found");
  75098. }
  75099. };
  75100. /**
  75101. * register a function that will be executed when this impostor collides against a different body.
  75102. */
  75103. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75104. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75105. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75106. };
  75107. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75108. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75109. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75110. if (index > -1) {
  75111. this._onPhysicsCollideCallbacks.splice(index, 1);
  75112. }
  75113. else {
  75114. BABYLON.Tools.Warn("Function to remove was not found");
  75115. }
  75116. };
  75117. PhysicsImpostor.prototype.getParentsRotation = function () {
  75118. var parent = this.object.parent;
  75119. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75120. while (parent) {
  75121. if (parent.rotationQuaternion) {
  75122. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75123. }
  75124. else {
  75125. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75126. }
  75127. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75128. parent = parent.parent;
  75129. }
  75130. return this._tmpQuat;
  75131. };
  75132. /**
  75133. * Apply a force
  75134. */
  75135. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75136. if (this._physicsEngine) {
  75137. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75138. }
  75139. return this;
  75140. };
  75141. /**
  75142. * Apply an impulse
  75143. */
  75144. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75145. if (this._physicsEngine) {
  75146. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75147. }
  75148. return this;
  75149. };
  75150. /**
  75151. * A help function to create a joint.
  75152. */
  75153. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75154. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75155. this.addJoint(otherImpostor, joint);
  75156. return this;
  75157. };
  75158. /**
  75159. * Add a joint to this impostor with a different impostor.
  75160. */
  75161. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75162. this._joints.push({
  75163. otherImpostor: otherImpostor,
  75164. joint: joint
  75165. });
  75166. if (this._physicsEngine) {
  75167. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75168. }
  75169. return this;
  75170. };
  75171. /**
  75172. * Will keep this body still, in a sleep mode.
  75173. */
  75174. PhysicsImpostor.prototype.sleep = function () {
  75175. if (this._physicsEngine) {
  75176. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75177. }
  75178. return this;
  75179. };
  75180. /**
  75181. * Wake the body up.
  75182. */
  75183. PhysicsImpostor.prototype.wakeUp = function () {
  75184. if (this._physicsEngine) {
  75185. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75186. }
  75187. return this;
  75188. };
  75189. PhysicsImpostor.prototype.clone = function (newObject) {
  75190. if (!newObject)
  75191. return null;
  75192. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75193. };
  75194. PhysicsImpostor.prototype.dispose = function () {
  75195. var _this = this;
  75196. //no dispose if no physics engine is available.
  75197. if (!this._physicsEngine) {
  75198. return;
  75199. }
  75200. this._joints.forEach(function (j) {
  75201. if (_this._physicsEngine) {
  75202. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75203. }
  75204. });
  75205. //dispose the physics body
  75206. this._physicsEngine.removeImpostor(this);
  75207. if (this.parent) {
  75208. this.parent.forceUpdate();
  75209. }
  75210. else {
  75211. /*this._object.getChildMeshes().forEach(function(mesh) {
  75212. if (mesh.physicsImpostor) {
  75213. if (disposeChildren) {
  75214. mesh.physicsImpostor.dispose();
  75215. mesh.physicsImpostor = null;
  75216. }
  75217. }
  75218. })*/
  75219. }
  75220. this._isDisposed = true;
  75221. };
  75222. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75223. this._deltaPosition.copyFrom(position);
  75224. };
  75225. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75226. if (!this._deltaRotation) {
  75227. this._deltaRotation = new BABYLON.Quaternion();
  75228. }
  75229. this._deltaRotation.copyFrom(rotation);
  75230. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75231. };
  75232. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75233. if (this._physicsEngine) {
  75234. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75235. }
  75236. return this;
  75237. };
  75238. PhysicsImpostor.prototype.getRadius = function () {
  75239. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75240. };
  75241. /**
  75242. * Sync a bone with this impostor
  75243. * @param bone The bone to sync to the impostor.
  75244. * @param boneMesh The mesh that the bone is influencing.
  75245. * @param jointPivot The pivot of the joint / bone in local space.
  75246. * @param distToJoint Optional distance from the impostor to the joint.
  75247. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75248. */
  75249. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75250. var tempVec = PhysicsImpostor._tmpVecs[0];
  75251. var mesh = this.object;
  75252. if (mesh.rotationQuaternion) {
  75253. if (adjustRotation) {
  75254. var tempQuat = PhysicsImpostor._tmpQuat;
  75255. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75256. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75257. }
  75258. else {
  75259. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75260. }
  75261. }
  75262. tempVec.x = 0;
  75263. tempVec.y = 0;
  75264. tempVec.z = 0;
  75265. if (jointPivot) {
  75266. tempVec.x = jointPivot.x;
  75267. tempVec.y = jointPivot.y;
  75268. tempVec.z = jointPivot.z;
  75269. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75270. if (distToJoint === undefined || distToJoint === null) {
  75271. distToJoint = jointPivot.length();
  75272. }
  75273. tempVec.x *= distToJoint;
  75274. tempVec.y *= distToJoint;
  75275. tempVec.z *= distToJoint;
  75276. }
  75277. if (bone.getParent()) {
  75278. tempVec.addInPlace(mesh.getAbsolutePosition());
  75279. bone.setAbsolutePosition(tempVec, boneMesh);
  75280. }
  75281. else {
  75282. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75283. boneMesh.position.x -= tempVec.x;
  75284. boneMesh.position.y -= tempVec.y;
  75285. boneMesh.position.z -= tempVec.z;
  75286. }
  75287. };
  75288. /**
  75289. * Sync impostor to a bone
  75290. * @param bone The bone that the impostor will be synced to.
  75291. * @param boneMesh The mesh that the bone is influencing.
  75292. * @param jointPivot The pivot of the joint / bone in local space.
  75293. * @param distToJoint Optional distance from the impostor to the joint.
  75294. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75295. * @param boneAxis Optional vector3 axis the bone is aligned with
  75296. */
  75297. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75298. var mesh = this.object;
  75299. if (mesh.rotationQuaternion) {
  75300. if (adjustRotation) {
  75301. var tempQuat = PhysicsImpostor._tmpQuat;
  75302. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75303. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75304. }
  75305. else {
  75306. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75307. }
  75308. }
  75309. var pos = PhysicsImpostor._tmpVecs[0];
  75310. var boneDir = PhysicsImpostor._tmpVecs[1];
  75311. if (!boneAxis) {
  75312. boneAxis = PhysicsImpostor._tmpVecs[2];
  75313. boneAxis.x = 0;
  75314. boneAxis.y = 1;
  75315. boneAxis.z = 0;
  75316. }
  75317. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75318. bone.getAbsolutePositionToRef(boneMesh, pos);
  75319. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75320. distToJoint = jointPivot.length();
  75321. }
  75322. if (distToJoint !== undefined && distToJoint !== null) {
  75323. pos.x += boneDir.x * distToJoint;
  75324. pos.y += boneDir.y * distToJoint;
  75325. pos.z += boneDir.z * distToJoint;
  75326. }
  75327. mesh.setAbsolutePosition(pos);
  75328. };
  75329. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75330. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75331. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75332. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75333. //Impostor types
  75334. PhysicsImpostor.NoImpostor = 0;
  75335. PhysicsImpostor.SphereImpostor = 1;
  75336. PhysicsImpostor.BoxImpostor = 2;
  75337. PhysicsImpostor.PlaneImpostor = 3;
  75338. PhysicsImpostor.MeshImpostor = 4;
  75339. PhysicsImpostor.CylinderImpostor = 7;
  75340. PhysicsImpostor.ParticleImpostor = 8;
  75341. PhysicsImpostor.HeightmapImpostor = 9;
  75342. return PhysicsImpostor;
  75343. }());
  75344. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75345. })(BABYLON || (BABYLON = {}));
  75346. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75347. var BABYLON;
  75348. (function (BABYLON) {
  75349. var PhysicsEngine = /** @class */ (function () {
  75350. function PhysicsEngine(gravity, _physicsPlugin) {
  75351. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75352. this._physicsPlugin = _physicsPlugin;
  75353. //new methods and parameters
  75354. this._impostors = [];
  75355. this._joints = [];
  75356. if (!this._physicsPlugin.isSupported()) {
  75357. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75358. + "Please make sure it is included.");
  75359. }
  75360. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75361. this.setGravity(gravity);
  75362. this.setTimeStep();
  75363. }
  75364. PhysicsEngine.prototype.setGravity = function (gravity) {
  75365. this.gravity = gravity;
  75366. this._physicsPlugin.setGravity(this.gravity);
  75367. };
  75368. /**
  75369. * Set the time step of the physics engine.
  75370. * default is 1/60.
  75371. * To slow it down, enter 1/600 for example.
  75372. * To speed it up, 1/30
  75373. * @param {number} newTimeStep the new timestep to apply to this world.
  75374. */
  75375. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75376. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75377. this._physicsPlugin.setTimeStep(newTimeStep);
  75378. };
  75379. /**
  75380. * Get the time step of the physics engine.
  75381. */
  75382. PhysicsEngine.prototype.getTimeStep = function () {
  75383. return this._physicsPlugin.getTimeStep();
  75384. };
  75385. PhysicsEngine.prototype.dispose = function () {
  75386. this._impostors.forEach(function (impostor) {
  75387. impostor.dispose();
  75388. });
  75389. this._physicsPlugin.dispose();
  75390. };
  75391. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75392. return this._physicsPlugin.name;
  75393. };
  75394. /**
  75395. * Adding a new impostor for the impostor tracking.
  75396. * This will be done by the impostor itself.
  75397. * @param {PhysicsImpostor} impostor the impostor to add
  75398. */
  75399. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75400. impostor.uniqueId = this._impostors.push(impostor);
  75401. //if no parent, generate the body
  75402. if (!impostor.parent) {
  75403. this._physicsPlugin.generatePhysicsBody(impostor);
  75404. }
  75405. };
  75406. /**
  75407. * Remove an impostor from the engine.
  75408. * This impostor and its mesh will not longer be updated by the physics engine.
  75409. * @param {PhysicsImpostor} impostor the impostor to remove
  75410. */
  75411. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75412. var index = this._impostors.indexOf(impostor);
  75413. if (index > -1) {
  75414. var removed = this._impostors.splice(index, 1);
  75415. //Is it needed?
  75416. if (removed.length) {
  75417. //this will also remove it from the world.
  75418. removed[0].physicsBody = null;
  75419. }
  75420. }
  75421. };
  75422. /**
  75423. * Add a joint to the physics engine
  75424. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75425. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75426. * @param {PhysicsJoint} the joint that will connect both impostors.
  75427. */
  75428. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75429. var impostorJoint = {
  75430. mainImpostor: mainImpostor,
  75431. connectedImpostor: connectedImpostor,
  75432. joint: joint
  75433. };
  75434. joint.physicsPlugin = this._physicsPlugin;
  75435. this._joints.push(impostorJoint);
  75436. this._physicsPlugin.generateJoint(impostorJoint);
  75437. };
  75438. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75439. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75440. return (impostorJoint.connectedImpostor === connectedImpostor
  75441. && impostorJoint.joint === joint
  75442. && impostorJoint.mainImpostor === mainImpostor);
  75443. });
  75444. if (matchingJoints.length) {
  75445. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75446. //TODO remove it from the list as well
  75447. }
  75448. };
  75449. /**
  75450. * Called by the scene. no need to call it.
  75451. */
  75452. PhysicsEngine.prototype._step = function (delta) {
  75453. var _this = this;
  75454. //check if any mesh has no body / requires an update
  75455. this._impostors.forEach(function (impostor) {
  75456. if (impostor.isBodyInitRequired()) {
  75457. _this._physicsPlugin.generatePhysicsBody(impostor);
  75458. }
  75459. });
  75460. if (delta > 0.1) {
  75461. delta = 0.1;
  75462. }
  75463. else if (delta <= 0) {
  75464. delta = 1.0 / 60.0;
  75465. }
  75466. this._physicsPlugin.executeStep(delta, this._impostors);
  75467. };
  75468. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75469. return this._physicsPlugin;
  75470. };
  75471. PhysicsEngine.prototype.getImpostors = function () {
  75472. return this._impostors;
  75473. };
  75474. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75475. for (var i = 0; i < this._impostors.length; ++i) {
  75476. if (this._impostors[i].object === object) {
  75477. return this._impostors[i];
  75478. }
  75479. }
  75480. return null;
  75481. };
  75482. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75483. for (var i = 0; i < this._impostors.length; ++i) {
  75484. if (this._impostors[i].physicsBody === body) {
  75485. return this._impostors[i];
  75486. }
  75487. }
  75488. return null;
  75489. };
  75490. // Statics
  75491. PhysicsEngine.Epsilon = 0.001;
  75492. return PhysicsEngine;
  75493. }());
  75494. BABYLON.PhysicsEngine = PhysicsEngine;
  75495. })(BABYLON || (BABYLON = {}));
  75496. //# sourceMappingURL=babylon.physicsEngine.js.map
  75497. var BABYLON;
  75498. (function (BABYLON) {
  75499. var PhysicsHelper = /** @class */ (function () {
  75500. function PhysicsHelper(scene) {
  75501. this._scene = scene;
  75502. this._physicsEngine = this._scene.getPhysicsEngine();
  75503. if (!this._physicsEngine) {
  75504. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75505. }
  75506. }
  75507. /**
  75508. * @param {Vector3} origin the origin of the explosion
  75509. * @param {number} radius the explosion radius
  75510. * @param {number} strength the explosion strength
  75511. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75512. */
  75513. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75514. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75515. if (!this._physicsEngine) {
  75516. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75517. return null;
  75518. }
  75519. var impostors = this._physicsEngine.getImpostors();
  75520. if (impostors.length === 0) {
  75521. return null;
  75522. }
  75523. var event = new PhysicsRadialExplosionEvent(this._scene);
  75524. impostors.forEach(function (impostor) {
  75525. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75526. if (!impostorForceAndContactPoint) {
  75527. return;
  75528. }
  75529. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75530. });
  75531. event.dispose(false);
  75532. return event;
  75533. };
  75534. /**
  75535. * @param {Vector3} origin the origin of the explosion
  75536. * @param {number} radius the explosion radius
  75537. * @param {number} strength the explosion strength
  75538. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75539. */
  75540. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75541. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75542. if (!this._physicsEngine) {
  75543. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75544. return null;
  75545. }
  75546. var impostors = this._physicsEngine.getImpostors();
  75547. if (impostors.length === 0) {
  75548. return null;
  75549. }
  75550. var event = new PhysicsRadialExplosionEvent(this._scene);
  75551. impostors.forEach(function (impostor) {
  75552. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75553. if (!impostorForceAndContactPoint) {
  75554. return;
  75555. }
  75556. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75557. });
  75558. event.dispose(false);
  75559. return event;
  75560. };
  75561. /**
  75562. * @param {Vector3} origin the origin of the explosion
  75563. * @param {number} radius the explosion radius
  75564. * @param {number} strength the explosion strength
  75565. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75566. */
  75567. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75568. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75569. if (!this._physicsEngine) {
  75570. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75571. return null;
  75572. }
  75573. var impostors = this._physicsEngine.getImpostors();
  75574. if (impostors.length === 0) {
  75575. return null;
  75576. }
  75577. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75578. event.dispose(false);
  75579. return event;
  75580. };
  75581. /**
  75582. * @param {Vector3} origin the origin of the updraft
  75583. * @param {number} radius the radius of the updraft
  75584. * @param {number} strength the strength of the updraft
  75585. * @param {number} height the height of the updraft
  75586. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75587. */
  75588. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75589. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75590. if (!this._physicsEngine) {
  75591. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75592. return null;
  75593. }
  75594. if (this._physicsEngine.getImpostors().length === 0) {
  75595. return null;
  75596. }
  75597. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75598. event.dispose(false);
  75599. return event;
  75600. };
  75601. /**
  75602. * @param {Vector3} origin the of the vortex
  75603. * @param {number} radius the radius of the vortex
  75604. * @param {number} strength the strength of the vortex
  75605. * @param {number} height the height of the vortex
  75606. */
  75607. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75608. if (!this._physicsEngine) {
  75609. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75610. return null;
  75611. }
  75612. if (this._physicsEngine.getImpostors().length === 0) {
  75613. return null;
  75614. }
  75615. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75616. event.dispose(false);
  75617. return event;
  75618. };
  75619. return PhysicsHelper;
  75620. }());
  75621. BABYLON.PhysicsHelper = PhysicsHelper;
  75622. /***** Radial explosion *****/
  75623. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75624. function PhysicsRadialExplosionEvent(scene) {
  75625. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75626. this._rays = [];
  75627. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75628. this._scene = scene;
  75629. }
  75630. /**
  75631. * Returns the data related to the radial explosion event (sphere & rays).
  75632. * @returns {PhysicsRadialExplosionEventData}
  75633. */
  75634. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75635. this._dataFetched = true;
  75636. return {
  75637. sphere: this._sphere,
  75638. rays: this._rays,
  75639. };
  75640. };
  75641. /**
  75642. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75643. * @param impostor
  75644. * @param {Vector3} origin the origin of the explosion
  75645. * @param {number} radius the explosion radius
  75646. * @param {number} strength the explosion strength
  75647. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75648. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75649. */
  75650. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75651. if (impostor.mass === 0) {
  75652. return null;
  75653. }
  75654. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75655. return null;
  75656. }
  75657. if (impostor.object.getClassName() !== 'Mesh') {
  75658. return null;
  75659. }
  75660. var impostorObject = impostor.object;
  75661. var impostorObjectCenter = impostor.getObjectCenter();
  75662. var direction = impostorObjectCenter.subtract(origin);
  75663. var ray = new BABYLON.Ray(origin, direction, radius);
  75664. this._rays.push(ray);
  75665. var hit = ray.intersectsMesh(impostorObject);
  75666. var contactPoint = hit.pickedPoint;
  75667. if (!contactPoint) {
  75668. return null;
  75669. }
  75670. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75671. if (distanceFromOrigin > radius) {
  75672. return null;
  75673. }
  75674. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75675. ? strength
  75676. : strength * (1 - (distanceFromOrigin / radius));
  75677. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75678. return { force: force, contactPoint: contactPoint };
  75679. };
  75680. /**
  75681. * Disposes the sphere.
  75682. * @param {bolean} force
  75683. */
  75684. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75685. var _this = this;
  75686. if (force === void 0) { force = true; }
  75687. if (force) {
  75688. this._sphere.dispose();
  75689. }
  75690. else {
  75691. setTimeout(function () {
  75692. if (!_this._dataFetched) {
  75693. _this._sphere.dispose();
  75694. }
  75695. }, 0);
  75696. }
  75697. };
  75698. /*** Helpers ***/
  75699. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75700. if (!this._sphere) {
  75701. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75702. this._sphere.isVisible = false;
  75703. }
  75704. };
  75705. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75706. var impostorObject = impostor.object;
  75707. this._prepareSphere();
  75708. this._sphere.position = origin;
  75709. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75710. this._sphere._updateBoundingInfo();
  75711. this._sphere.computeWorldMatrix(true);
  75712. return this._sphere.intersectsMesh(impostorObject, true);
  75713. };
  75714. return PhysicsRadialExplosionEvent;
  75715. }());
  75716. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75717. /***** Gravitational Field *****/
  75718. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75719. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75720. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75721. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75722. this._physicsHelper = physicsHelper;
  75723. this._scene = scene;
  75724. this._origin = origin;
  75725. this._radius = radius;
  75726. this._strength = strength;
  75727. this._falloff = falloff;
  75728. this._tickCallback = this._tick.bind(this);
  75729. }
  75730. /**
  75731. * Returns the data related to the gravitational field event (sphere).
  75732. * @returns {PhysicsGravitationalFieldEventData}
  75733. */
  75734. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75735. this._dataFetched = true;
  75736. return {
  75737. sphere: this._sphere,
  75738. };
  75739. };
  75740. /**
  75741. * Enables the gravitational field.
  75742. */
  75743. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75744. this._tickCallback.call(this);
  75745. this._scene.registerBeforeRender(this._tickCallback);
  75746. };
  75747. /**
  75748. * Disables the gravitational field.
  75749. */
  75750. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75751. this._scene.unregisterBeforeRender(this._tickCallback);
  75752. };
  75753. /**
  75754. * Disposes the sphere.
  75755. * @param {bolean} force
  75756. */
  75757. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75758. var _this = this;
  75759. if (force === void 0) { force = true; }
  75760. if (force) {
  75761. this._sphere.dispose();
  75762. }
  75763. else {
  75764. setTimeout(function () {
  75765. if (!_this._dataFetched) {
  75766. _this._sphere.dispose();
  75767. }
  75768. }, 0);
  75769. }
  75770. };
  75771. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75772. // Since the params won't change, we fetch the event only once
  75773. if (this._sphere) {
  75774. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75775. }
  75776. else {
  75777. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75778. if (radialExplosionEvent) {
  75779. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75780. }
  75781. }
  75782. };
  75783. return PhysicsGravitationalFieldEvent;
  75784. }());
  75785. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75786. /***** Updraft *****/
  75787. var PhysicsUpdraftEvent = /** @class */ (function () {
  75788. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75789. this._scene = _scene;
  75790. this._origin = _origin;
  75791. this._radius = _radius;
  75792. this._strength = _strength;
  75793. this._height = _height;
  75794. this._updraftMode = _updraftMode;
  75795. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75796. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75797. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75798. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75799. this._physicsEngine = this._scene.getPhysicsEngine();
  75800. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75801. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75802. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75803. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75804. }
  75805. this._tickCallback = this._tick.bind(this);
  75806. }
  75807. /**
  75808. * Returns the data related to the updraft event (cylinder).
  75809. * @returns {PhysicsUpdraftEventData}
  75810. */
  75811. PhysicsUpdraftEvent.prototype.getData = function () {
  75812. this._dataFetched = true;
  75813. return {
  75814. cylinder: this._cylinder,
  75815. };
  75816. };
  75817. /**
  75818. * Enables the updraft.
  75819. */
  75820. PhysicsUpdraftEvent.prototype.enable = function () {
  75821. this._tickCallback.call(this);
  75822. this._scene.registerBeforeRender(this._tickCallback);
  75823. };
  75824. /**
  75825. * Disables the cortex.
  75826. */
  75827. PhysicsUpdraftEvent.prototype.disable = function () {
  75828. this._scene.unregisterBeforeRender(this._tickCallback);
  75829. };
  75830. /**
  75831. * Disposes the sphere.
  75832. * @param {bolean} force
  75833. */
  75834. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75835. var _this = this;
  75836. if (force === void 0) { force = true; }
  75837. if (force) {
  75838. this._cylinder.dispose();
  75839. }
  75840. else {
  75841. setTimeout(function () {
  75842. if (!_this._dataFetched) {
  75843. _this._cylinder.dispose();
  75844. }
  75845. }, 0);
  75846. }
  75847. };
  75848. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75849. if (impostor.mass === 0) {
  75850. return null;
  75851. }
  75852. if (!this._intersectsWithCylinder(impostor)) {
  75853. return null;
  75854. }
  75855. var impostorObjectCenter = impostor.getObjectCenter();
  75856. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75857. var direction = this._originDirection;
  75858. }
  75859. else {
  75860. var direction = impostorObjectCenter.subtract(this._originTop);
  75861. }
  75862. var multiplier = this._strength * -1;
  75863. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75864. return { force: force, contactPoint: impostorObjectCenter };
  75865. };
  75866. PhysicsUpdraftEvent.prototype._tick = function () {
  75867. var _this = this;
  75868. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75869. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75870. if (!impostorForceAndContactPoint) {
  75871. return;
  75872. }
  75873. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75874. });
  75875. };
  75876. /*** Helpers ***/
  75877. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75878. if (!this._cylinder) {
  75879. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75880. height: this._height,
  75881. diameter: this._radius * 2,
  75882. }, this._scene);
  75883. this._cylinder.isVisible = false;
  75884. }
  75885. };
  75886. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75887. var impostorObject = impostor.object;
  75888. this._prepareCylinder();
  75889. this._cylinder.position = this._cylinderPosition;
  75890. return this._cylinder.intersectsMesh(impostorObject, true);
  75891. };
  75892. return PhysicsUpdraftEvent;
  75893. }());
  75894. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75895. /***** Vortex *****/
  75896. var PhysicsVortexEvent = /** @class */ (function () {
  75897. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75898. this._scene = _scene;
  75899. this._origin = _origin;
  75900. this._radius = _radius;
  75901. this._strength = _strength;
  75902. this._height = _height;
  75903. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75904. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75905. this._updraftMultiplier = 0.02;
  75906. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75907. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75908. this._physicsEngine = this._scene.getPhysicsEngine();
  75909. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75910. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75911. this._tickCallback = this._tick.bind(this);
  75912. }
  75913. /**
  75914. * Returns the data related to the vortex event (cylinder).
  75915. * @returns {PhysicsVortexEventData}
  75916. */
  75917. PhysicsVortexEvent.prototype.getData = function () {
  75918. this._dataFetched = true;
  75919. return {
  75920. cylinder: this._cylinder,
  75921. };
  75922. };
  75923. /**
  75924. * Enables the vortex.
  75925. */
  75926. PhysicsVortexEvent.prototype.enable = function () {
  75927. this._tickCallback.call(this);
  75928. this._scene.registerBeforeRender(this._tickCallback);
  75929. };
  75930. /**
  75931. * Disables the cortex.
  75932. */
  75933. PhysicsVortexEvent.prototype.disable = function () {
  75934. this._scene.unregisterBeforeRender(this._tickCallback);
  75935. };
  75936. /**
  75937. * Disposes the sphere.
  75938. * @param {bolean} force
  75939. */
  75940. PhysicsVortexEvent.prototype.dispose = function (force) {
  75941. var _this = this;
  75942. if (force === void 0) { force = true; }
  75943. if (force) {
  75944. this._cylinder.dispose();
  75945. }
  75946. else {
  75947. setTimeout(function () {
  75948. if (!_this._dataFetched) {
  75949. _this._cylinder.dispose();
  75950. }
  75951. }, 0);
  75952. }
  75953. };
  75954. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75955. if (impostor.mass === 0) {
  75956. return null;
  75957. }
  75958. if (!this._intersectsWithCylinder(impostor)) {
  75959. return null;
  75960. }
  75961. if (impostor.object.getClassName() !== 'Mesh') {
  75962. return null;
  75963. }
  75964. var impostorObject = impostor.object;
  75965. var impostorObjectCenter = impostor.getObjectCenter();
  75966. 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)
  75967. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75968. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75969. var hit = ray.intersectsMesh(impostorObject);
  75970. var contactPoint = hit.pickedPoint;
  75971. if (!contactPoint) {
  75972. return null;
  75973. }
  75974. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75975. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75976. var directionToOrigin = contactPoint.normalize();
  75977. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75978. directionToOrigin = directionToOrigin.negate();
  75979. }
  75980. // TODO: find a more physically based solution
  75981. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75982. var forceX = directionToOrigin.x * this._strength / 8;
  75983. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75984. var forceZ = directionToOrigin.z * this._strength / 8;
  75985. }
  75986. else {
  75987. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75988. var forceY = this._originTop.y * this._updraftMultiplier;
  75989. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75990. }
  75991. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75992. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75993. return { force: force, contactPoint: impostorObjectCenter };
  75994. };
  75995. PhysicsVortexEvent.prototype._tick = function () {
  75996. var _this = this;
  75997. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75998. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75999. if (!impostorForceAndContactPoint) {
  76000. return;
  76001. }
  76002. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76003. });
  76004. };
  76005. /*** Helpers ***/
  76006. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76007. if (!this._cylinder) {
  76008. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76009. height: this._height,
  76010. diameter: this._radius * 2,
  76011. }, this._scene);
  76012. this._cylinder.isVisible = false;
  76013. }
  76014. };
  76015. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76016. var impostorObject = impostor.object;
  76017. this._prepareCylinder();
  76018. this._cylinder.position = this._cylinderPosition;
  76019. return this._cylinder.intersectsMesh(impostorObject, true);
  76020. };
  76021. return PhysicsVortexEvent;
  76022. }());
  76023. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76024. /***** Enums *****/
  76025. /**
  76026. * The strenght of the force in correspondence to the distance of the affected object
  76027. */
  76028. var PhysicsRadialImpulseFalloff;
  76029. (function (PhysicsRadialImpulseFalloff) {
  76030. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76031. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76032. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76033. /**
  76034. * The strenght of the force in correspondence to the distance of the affected object
  76035. */
  76036. var PhysicsUpdraftMode;
  76037. (function (PhysicsUpdraftMode) {
  76038. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76039. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76040. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76041. })(BABYLON || (BABYLON = {}));
  76042. //# sourceMappingURL=babylon.physicsHelper.js.map
  76043. var BABYLON;
  76044. (function (BABYLON) {
  76045. var CannonJSPlugin = /** @class */ (function () {
  76046. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76047. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76048. if (iterations === void 0) { iterations = 10; }
  76049. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76050. this.name = "CannonJSPlugin";
  76051. this._physicsMaterials = new Array();
  76052. this._fixedTimeStep = 1 / 60;
  76053. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76054. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76055. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76056. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76057. this._tmpPosition = BABYLON.Vector3.Zero();
  76058. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76059. this._tmpUnityRotation = new BABYLON.Quaternion();
  76060. if (!this.isSupported()) {
  76061. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76062. return;
  76063. }
  76064. this._extendNamespace();
  76065. this.world = new this.BJSCANNON.World();
  76066. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76067. this.world.solver.iterations = iterations;
  76068. }
  76069. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76070. this.world.gravity.copy(gravity);
  76071. };
  76072. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76073. this._fixedTimeStep = timeStep;
  76074. };
  76075. CannonJSPlugin.prototype.getTimeStep = function () {
  76076. return this._fixedTimeStep;
  76077. };
  76078. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76079. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76080. };
  76081. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76082. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76083. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76084. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76085. };
  76086. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76087. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76088. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76089. impostor.physicsBody.applyForce(impulse, worldPoint);
  76090. };
  76091. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76092. //parent-child relationship. Does this impostor has a parent impostor?
  76093. if (impostor.parent) {
  76094. if (impostor.physicsBody) {
  76095. this.removePhysicsBody(impostor);
  76096. //TODO is that needed?
  76097. impostor.forceUpdate();
  76098. }
  76099. return;
  76100. }
  76101. //should a new body be created for this impostor?
  76102. if (impostor.isBodyInitRequired()) {
  76103. var shape = this._createShape(impostor);
  76104. //unregister events, if body is being changed
  76105. var oldBody = impostor.physicsBody;
  76106. if (oldBody) {
  76107. this.removePhysicsBody(impostor);
  76108. }
  76109. //create the body and material
  76110. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76111. var bodyCreationObject = {
  76112. mass: impostor.getParam("mass"),
  76113. material: material
  76114. };
  76115. // A simple extend, in case native options were used.
  76116. var nativeOptions = impostor.getParam("nativeOptions");
  76117. for (var key in nativeOptions) {
  76118. if (nativeOptions.hasOwnProperty(key)) {
  76119. bodyCreationObject[key] = nativeOptions[key];
  76120. }
  76121. }
  76122. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76123. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76124. this.world.addEventListener("preStep", impostor.beforeStep);
  76125. this.world.addEventListener("postStep", impostor.afterStep);
  76126. impostor.physicsBody.addShape(shape);
  76127. this.world.add(impostor.physicsBody);
  76128. //try to keep the body moving in the right direction by taking old properties.
  76129. //Should be tested!
  76130. if (oldBody) {
  76131. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76132. impostor.physicsBody[param].copy(oldBody[param]);
  76133. });
  76134. }
  76135. this._processChildMeshes(impostor);
  76136. }
  76137. //now update the body's transformation
  76138. this._updatePhysicsBodyTransformation(impostor);
  76139. };
  76140. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76141. var _this = this;
  76142. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76143. var currentRotation = mainImpostor.object.rotationQuaternion;
  76144. if (meshChildren.length) {
  76145. var processMesh = function (localPosition, mesh) {
  76146. if (!currentRotation || !mesh.rotationQuaternion) {
  76147. return;
  76148. }
  76149. var childImpostor = mesh.getPhysicsImpostor();
  76150. if (childImpostor) {
  76151. var parent = childImpostor.parent;
  76152. if (parent !== mainImpostor) {
  76153. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76154. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76155. if (childImpostor.physicsBody) {
  76156. _this.removePhysicsBody(childImpostor);
  76157. childImpostor.physicsBody = null;
  76158. }
  76159. childImpostor.parent = mainImpostor;
  76160. childImpostor.resetUpdateFlags();
  76161. 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));
  76162. //Add the mass of the children.
  76163. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76164. }
  76165. }
  76166. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76167. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76168. };
  76169. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76170. }
  76171. };
  76172. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76173. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76174. this.world.removeEventListener("preStep", impostor.beforeStep);
  76175. this.world.removeEventListener("postStep", impostor.afterStep);
  76176. this.world.remove(impostor.physicsBody);
  76177. };
  76178. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76179. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76180. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76181. if (!mainBody || !connectedBody) {
  76182. return;
  76183. }
  76184. var constraint;
  76185. var jointData = impostorJoint.joint.jointData;
  76186. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76187. var constraintData = {
  76188. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76189. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76190. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76191. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76192. maxForce: jointData.nativeParams.maxForce,
  76193. collideConnected: !!jointData.collision
  76194. };
  76195. switch (impostorJoint.joint.type) {
  76196. case BABYLON.PhysicsJoint.HingeJoint:
  76197. case BABYLON.PhysicsJoint.Hinge2Joint:
  76198. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76199. break;
  76200. case BABYLON.PhysicsJoint.DistanceJoint:
  76201. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76202. break;
  76203. case BABYLON.PhysicsJoint.SpringJoint:
  76204. var springData = jointData;
  76205. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76206. restLength: springData.length,
  76207. stiffness: springData.stiffness,
  76208. damping: springData.damping,
  76209. localAnchorA: constraintData.pivotA,
  76210. localAnchorB: constraintData.pivotB
  76211. });
  76212. break;
  76213. case BABYLON.PhysicsJoint.LockJoint:
  76214. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76215. break;
  76216. case BABYLON.PhysicsJoint.PointToPointJoint:
  76217. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76218. default:
  76219. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76220. break;
  76221. }
  76222. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76223. constraint.collideConnected = !!jointData.collision;
  76224. impostorJoint.joint.physicsJoint = constraint;
  76225. //don't add spring as constraint, as it is not one.
  76226. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76227. this.world.addConstraint(constraint);
  76228. }
  76229. else {
  76230. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76231. constraint.applyForce();
  76232. });
  76233. }
  76234. };
  76235. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76236. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76237. };
  76238. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76239. var index;
  76240. var mat;
  76241. for (index = 0; index < this._physicsMaterials.length; index++) {
  76242. mat = this._physicsMaterials[index];
  76243. if (mat.friction === friction && mat.restitution === restitution) {
  76244. return mat;
  76245. }
  76246. }
  76247. var currentMat = new this.BJSCANNON.Material(name);
  76248. currentMat.friction = friction;
  76249. currentMat.restitution = restitution;
  76250. this._physicsMaterials.push(currentMat);
  76251. return currentMat;
  76252. };
  76253. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76254. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76255. };
  76256. CannonJSPlugin.prototype._createShape = function (impostor) {
  76257. var object = impostor.object;
  76258. var returnValue;
  76259. var extendSize = impostor.getObjectExtendSize();
  76260. switch (impostor.type) {
  76261. case BABYLON.PhysicsImpostor.SphereImpostor:
  76262. var radiusX = extendSize.x;
  76263. var radiusY = extendSize.y;
  76264. var radiusZ = extendSize.z;
  76265. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76266. break;
  76267. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76268. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76269. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76270. break;
  76271. case BABYLON.PhysicsImpostor.BoxImpostor:
  76272. var box = extendSize.scale(0.5);
  76273. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76274. break;
  76275. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76276. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76277. returnValue = new this.BJSCANNON.Plane();
  76278. break;
  76279. case BABYLON.PhysicsImpostor.MeshImpostor:
  76280. // should transform the vertex data to world coordinates!!
  76281. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76282. var rawFaces = object.getIndices ? object.getIndices() : [];
  76283. if (!rawVerts)
  76284. return;
  76285. // get only scale! so the object could transform correctly.
  76286. var oldPosition = object.position.clone();
  76287. var oldRotation = object.rotation && object.rotation.clone();
  76288. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76289. object.position.copyFromFloats(0, 0, 0);
  76290. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76291. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76292. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76293. var transform = object.computeWorldMatrix(true);
  76294. // convert rawVerts to object space
  76295. var temp = new Array();
  76296. var index;
  76297. for (index = 0; index < rawVerts.length; index += 3) {
  76298. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76299. }
  76300. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76301. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76302. //now set back the transformation!
  76303. object.position.copyFrom(oldPosition);
  76304. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76305. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76306. break;
  76307. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76308. var oldPosition2 = object.position.clone();
  76309. var oldRotation2 = object.rotation && object.rotation.clone();
  76310. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76311. object.position.copyFromFloats(0, 0, 0);
  76312. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76313. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76314. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76315. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76316. returnValue = this._createHeightmap(object);
  76317. object.position.copyFrom(oldPosition2);
  76318. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76319. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76320. object.computeWorldMatrix(true);
  76321. break;
  76322. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76323. returnValue = new this.BJSCANNON.Particle();
  76324. break;
  76325. }
  76326. return returnValue;
  76327. };
  76328. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76329. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76330. var transform = object.computeWorldMatrix(true);
  76331. // convert rawVerts to object space
  76332. var temp = new Array();
  76333. var index;
  76334. for (index = 0; index < pos.length; index += 3) {
  76335. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76336. }
  76337. pos = temp;
  76338. var matrix = new Array();
  76339. //For now pointDepth will not be used and will be automatically calculated.
  76340. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76341. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76342. var boundingInfo = object.getBoundingInfo();
  76343. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76344. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76345. var elementSize = dim * 2 / arraySize;
  76346. for (var i = 0; i < pos.length; i = i + 3) {
  76347. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76348. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76349. var y = -pos[i + 2] + minY;
  76350. if (!matrix[x]) {
  76351. matrix[x] = [];
  76352. }
  76353. if (!matrix[x][z]) {
  76354. matrix[x][z] = y;
  76355. }
  76356. matrix[x][z] = Math.max(y, matrix[x][z]);
  76357. }
  76358. for (var x = 0; x <= arraySize; ++x) {
  76359. if (!matrix[x]) {
  76360. var loc = 1;
  76361. while (!matrix[(x + loc) % arraySize]) {
  76362. loc++;
  76363. }
  76364. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76365. //console.log("missing x", x);
  76366. }
  76367. for (var z = 0; z <= arraySize; ++z) {
  76368. if (!matrix[x][z]) {
  76369. var loc = 1;
  76370. var newValue;
  76371. while (newValue === undefined) {
  76372. newValue = matrix[x][(z + loc++) % arraySize];
  76373. }
  76374. matrix[x][z] = newValue;
  76375. }
  76376. }
  76377. }
  76378. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76379. elementSize: elementSize
  76380. });
  76381. //For future reference, needed for body transformation
  76382. shape.minY = minY;
  76383. return shape;
  76384. };
  76385. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76386. var object = impostor.object;
  76387. //make sure it is updated...
  76388. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76389. // The delta between the mesh position and the mesh bounding box center
  76390. var bInfo = object.getBoundingInfo();
  76391. if (!bInfo)
  76392. return;
  76393. var center = impostor.getObjectCenter();
  76394. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76395. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76396. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76397. this._tmpPosition.copyFrom(center);
  76398. var quaternion = object.rotationQuaternion;
  76399. if (!quaternion) {
  76400. return;
  76401. }
  76402. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76403. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76404. //-90 DEG in X, precalculated
  76405. quaternion = quaternion.multiply(this._minus90X);
  76406. //Invert! (Precalculated, 90 deg in X)
  76407. //No need to clone. this will never change.
  76408. impostor.setDeltaRotation(this._plus90X);
  76409. }
  76410. //If it is a heightfield, if should be centered.
  76411. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76412. var mesh = object;
  76413. var boundingInfo = mesh.getBoundingInfo();
  76414. //calculate the correct body position:
  76415. var rotationQuaternion = mesh.rotationQuaternion;
  76416. mesh.rotationQuaternion = this._tmpUnityRotation;
  76417. mesh.computeWorldMatrix(true);
  76418. //get original center with no rotation
  76419. var c = center.clone();
  76420. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76421. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76422. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76423. mesh.setPreTransformMatrix(p);
  76424. mesh.computeWorldMatrix(true);
  76425. //calculate the translation
  76426. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76427. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76428. //add it inverted to the delta
  76429. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76430. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76431. //rotation is back
  76432. mesh.rotationQuaternion = rotationQuaternion;
  76433. mesh.setPreTransformMatrix(oldPivot);
  76434. mesh.computeWorldMatrix(true);
  76435. }
  76436. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76437. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76438. //this._tmpPosition.copyFrom(object.position);
  76439. }
  76440. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76441. //Now update the impostor object
  76442. impostor.physicsBody.position.copy(this._tmpPosition);
  76443. impostor.physicsBody.quaternion.copy(quaternion);
  76444. };
  76445. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76446. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76447. if (impostor.object.rotationQuaternion) {
  76448. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76449. }
  76450. };
  76451. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76452. impostor.physicsBody.position.copy(newPosition);
  76453. impostor.physicsBody.quaternion.copy(newRotation);
  76454. };
  76455. CannonJSPlugin.prototype.isSupported = function () {
  76456. return this.BJSCANNON !== undefined;
  76457. };
  76458. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76459. impostor.physicsBody.velocity.copy(velocity);
  76460. };
  76461. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76462. impostor.physicsBody.angularVelocity.copy(velocity);
  76463. };
  76464. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76465. var v = impostor.physicsBody.velocity;
  76466. if (!v) {
  76467. return null;
  76468. }
  76469. return new BABYLON.Vector3(v.x, v.y, v.z);
  76470. };
  76471. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76472. var v = impostor.physicsBody.angularVelocity;
  76473. if (!v) {
  76474. return null;
  76475. }
  76476. return new BABYLON.Vector3(v.x, v.y, v.z);
  76477. };
  76478. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76479. impostor.physicsBody.mass = mass;
  76480. impostor.physicsBody.updateMassProperties();
  76481. };
  76482. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76483. return impostor.physicsBody.mass;
  76484. };
  76485. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76486. return impostor.physicsBody.material.friction;
  76487. };
  76488. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76489. impostor.physicsBody.material.friction = friction;
  76490. };
  76491. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76492. return impostor.physicsBody.material.restitution;
  76493. };
  76494. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76495. impostor.physicsBody.material.restitution = restitution;
  76496. };
  76497. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76498. impostor.physicsBody.sleep();
  76499. };
  76500. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76501. impostor.physicsBody.wakeUp();
  76502. };
  76503. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76504. joint.physicsJoint.distance = maxDistance;
  76505. };
  76506. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76507. // if (!motorIndex) {
  76508. // joint.physicsJoint.enableMotor();
  76509. // }
  76510. // }
  76511. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76512. // if (!motorIndex) {
  76513. // joint.physicsJoint.disableMotor();
  76514. // }
  76515. // }
  76516. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76517. if (!motorIndex) {
  76518. joint.physicsJoint.enableMotor();
  76519. joint.physicsJoint.setMotorSpeed(speed);
  76520. if (maxForce) {
  76521. this.setLimit(joint, maxForce);
  76522. }
  76523. }
  76524. };
  76525. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76526. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76527. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76528. };
  76529. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76530. var body = impostor.physicsBody;
  76531. mesh.position.x = body.position.x;
  76532. mesh.position.y = body.position.y;
  76533. mesh.position.z = body.position.z;
  76534. if (mesh.rotationQuaternion) {
  76535. mesh.rotationQuaternion.x = body.quaternion.x;
  76536. mesh.rotationQuaternion.y = body.quaternion.y;
  76537. mesh.rotationQuaternion.z = body.quaternion.z;
  76538. mesh.rotationQuaternion.w = body.quaternion.w;
  76539. }
  76540. };
  76541. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76542. var shape = impostor.physicsBody.shapes[0];
  76543. return shape.boundingSphereRadius;
  76544. };
  76545. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76546. var shape = impostor.physicsBody.shapes[0];
  76547. result.x = shape.halfExtents.x * 2;
  76548. result.y = shape.halfExtents.y * 2;
  76549. result.z = shape.halfExtents.z * 2;
  76550. };
  76551. CannonJSPlugin.prototype.dispose = function () {
  76552. };
  76553. CannonJSPlugin.prototype._extendNamespace = function () {
  76554. //this will force cannon to execute at least one step when using interpolation
  76555. var step_tmp1 = new this.BJSCANNON.Vec3();
  76556. var Engine = this.BJSCANNON;
  76557. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76558. maxSubSteps = maxSubSteps || 10;
  76559. timeSinceLastCalled = timeSinceLastCalled || 0;
  76560. if (timeSinceLastCalled === 0) {
  76561. this.internalStep(dt);
  76562. this.time += dt;
  76563. }
  76564. else {
  76565. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76566. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76567. var t0 = performance.now();
  76568. for (var i = 0; i !== internalSteps; i++) {
  76569. this.internalStep(dt);
  76570. if (performance.now() - t0 > dt * 1000) {
  76571. break;
  76572. }
  76573. }
  76574. this.time += timeSinceLastCalled;
  76575. var h = this.time % dt;
  76576. var h_div_dt = h / dt;
  76577. var interpvelo = step_tmp1;
  76578. var bodies = this.bodies;
  76579. for (var j = 0; j !== bodies.length; j++) {
  76580. var b = bodies[j];
  76581. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76582. b.position.vsub(b.previousPosition, interpvelo);
  76583. interpvelo.scale(h_div_dt, interpvelo);
  76584. b.position.vadd(interpvelo, b.interpolatedPosition);
  76585. }
  76586. else {
  76587. b.interpolatedPosition.copy(b.position);
  76588. b.interpolatedQuaternion.copy(b.quaternion);
  76589. }
  76590. }
  76591. }
  76592. };
  76593. };
  76594. return CannonJSPlugin;
  76595. }());
  76596. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76597. })(BABYLON || (BABYLON = {}));
  76598. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76599. var BABYLON;
  76600. (function (BABYLON) {
  76601. var OimoJSPlugin = /** @class */ (function () {
  76602. function OimoJSPlugin(iterations) {
  76603. this.name = "OimoJSPlugin";
  76604. this._tmpImpostorsArray = [];
  76605. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76606. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76607. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76608. this.world.worldscale(1);
  76609. this.world.clear();
  76610. //making sure no stats are calculated
  76611. this.world.isNoStat = true;
  76612. }
  76613. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76614. this.world.gravity.copy(gravity);
  76615. };
  76616. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76617. this.world.timeStep = timeStep;
  76618. };
  76619. OimoJSPlugin.prototype.getTimeStep = function () {
  76620. return this.world.timeStep;
  76621. };
  76622. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76623. var _this = this;
  76624. impostors.forEach(function (impostor) {
  76625. impostor.beforeStep();
  76626. });
  76627. this.world.step();
  76628. impostors.forEach(function (impostor) {
  76629. impostor.afterStep();
  76630. //update the ordered impostors array
  76631. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76632. });
  76633. //check for collisions
  76634. var contact = this.world.contacts;
  76635. while (contact !== null) {
  76636. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76637. contact = contact.next;
  76638. continue;
  76639. }
  76640. //is this body colliding with any other? get the impostor
  76641. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76642. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76643. if (!mainImpostor || !collidingImpostor) {
  76644. contact = contact.next;
  76645. continue;
  76646. }
  76647. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76648. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76649. contact = contact.next;
  76650. }
  76651. };
  76652. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76653. var mass = impostor.physicsBody.massInfo.mass;
  76654. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76655. };
  76656. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76657. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76658. this.applyImpulse(impostor, force, contactPoint);
  76659. };
  76660. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76661. var _this = this;
  76662. //parent-child relationship. Does this impostor has a parent impostor?
  76663. if (impostor.parent) {
  76664. if (impostor.physicsBody) {
  76665. this.removePhysicsBody(impostor);
  76666. //TODO is that needed?
  76667. impostor.forceUpdate();
  76668. }
  76669. return;
  76670. }
  76671. if (impostor.isBodyInitRequired()) {
  76672. var bodyConfig = {
  76673. name: impostor.uniqueId,
  76674. //Oimo must have mass, also for static objects.
  76675. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76676. size: [],
  76677. type: [],
  76678. pos: [],
  76679. rot: [],
  76680. move: impostor.getParam("mass") !== 0,
  76681. //Supporting older versions of Oimo
  76682. world: this.world
  76683. };
  76684. var impostors = [impostor];
  76685. var addToArray = function (parent) {
  76686. if (!parent.getChildMeshes)
  76687. return;
  76688. parent.getChildMeshes().forEach(function (m) {
  76689. if (m.physicsImpostor) {
  76690. impostors.push(m.physicsImpostor);
  76691. //m.physicsImpostor._init();
  76692. }
  76693. });
  76694. };
  76695. addToArray(impostor.object);
  76696. var checkWithEpsilon_1 = function (value) {
  76697. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76698. };
  76699. impostors.forEach(function (i) {
  76700. if (!impostor.object.rotationQuaternion) {
  76701. return;
  76702. }
  76703. //get the correct bounding box
  76704. var oldQuaternion = i.object.rotationQuaternion;
  76705. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76706. x: impostor.object.rotationQuaternion.x,
  76707. y: impostor.object.rotationQuaternion.y,
  76708. z: impostor.object.rotationQuaternion.z,
  76709. s: impostor.object.rotationQuaternion.w
  76710. });
  76711. var extendSize = i.getObjectExtendSize();
  76712. if (i === impostor) {
  76713. var center = impostor.getObjectCenter();
  76714. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76715. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76716. //Can also use Array.prototype.push.apply
  76717. bodyConfig.pos.push(center.x);
  76718. bodyConfig.pos.push(center.y);
  76719. bodyConfig.pos.push(center.z);
  76720. //tmp solution
  76721. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76722. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76723. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76724. }
  76725. else {
  76726. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76727. bodyConfig.pos.push(localPosition.x);
  76728. bodyConfig.pos.push(localPosition.y);
  76729. bodyConfig.pos.push(localPosition.z);
  76730. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76731. bodyConfig.rot.push(0);
  76732. bodyConfig.rot.push(0);
  76733. bodyConfig.rot.push(0);
  76734. }
  76735. // register mesh
  76736. switch (i.type) {
  76737. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76738. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76739. case BABYLON.PhysicsImpostor.SphereImpostor:
  76740. var radiusX = extendSize.x;
  76741. var radiusY = extendSize.y;
  76742. var radiusZ = extendSize.z;
  76743. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76744. bodyConfig.type.push('sphere');
  76745. //due to the way oimo works with compounds, add 3 times
  76746. bodyConfig.size.push(size);
  76747. bodyConfig.size.push(size);
  76748. bodyConfig.size.push(size);
  76749. break;
  76750. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76751. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76752. var sizeY = checkWithEpsilon_1(extendSize.y);
  76753. bodyConfig.type.push('cylinder');
  76754. bodyConfig.size.push(sizeX);
  76755. bodyConfig.size.push(sizeY);
  76756. //due to the way oimo works with compounds, add one more value.
  76757. bodyConfig.size.push(sizeY);
  76758. break;
  76759. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76760. case BABYLON.PhysicsImpostor.BoxImpostor:
  76761. default:
  76762. var sizeX = checkWithEpsilon_1(extendSize.x);
  76763. var sizeY = checkWithEpsilon_1(extendSize.y);
  76764. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76765. bodyConfig.type.push('box');
  76766. bodyConfig.size.push(sizeX);
  76767. bodyConfig.size.push(sizeY);
  76768. bodyConfig.size.push(sizeZ);
  76769. break;
  76770. }
  76771. //actually not needed, but hey...
  76772. i.object.rotationQuaternion = oldQuaternion;
  76773. });
  76774. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76775. }
  76776. else {
  76777. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76778. }
  76779. impostor.setDeltaPosition(this._tmpPositionVector);
  76780. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76781. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76782. };
  76783. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76784. //impostor.physicsBody.dispose();
  76785. //Same as : (older oimo versions)
  76786. this.world.removeRigidBody(impostor.physicsBody);
  76787. };
  76788. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76789. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76790. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76791. if (!mainBody || !connectedBody) {
  76792. return;
  76793. }
  76794. var jointData = impostorJoint.joint.jointData;
  76795. var options = jointData.nativeParams || {};
  76796. var type;
  76797. var nativeJointData = {
  76798. body1: mainBody,
  76799. body2: connectedBody,
  76800. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76801. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76802. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76803. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76804. min: options.min,
  76805. max: options.max,
  76806. collision: options.collision || jointData.collision,
  76807. spring: options.spring,
  76808. //supporting older version of Oimo
  76809. world: this.world
  76810. };
  76811. switch (impostorJoint.joint.type) {
  76812. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76813. type = "jointBall";
  76814. break;
  76815. case BABYLON.PhysicsJoint.SpringJoint:
  76816. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76817. var springData = jointData;
  76818. nativeJointData.min = springData.length || nativeJointData.min;
  76819. //Max should also be set, just make sure it is at least min
  76820. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76821. case BABYLON.PhysicsJoint.DistanceJoint:
  76822. type = "jointDistance";
  76823. nativeJointData.max = jointData.maxDistance;
  76824. break;
  76825. case BABYLON.PhysicsJoint.PrismaticJoint:
  76826. type = "jointPrisme";
  76827. break;
  76828. case BABYLON.PhysicsJoint.SliderJoint:
  76829. type = "jointSlide";
  76830. break;
  76831. case BABYLON.PhysicsJoint.WheelJoint:
  76832. type = "jointWheel";
  76833. break;
  76834. case BABYLON.PhysicsJoint.HingeJoint:
  76835. default:
  76836. type = "jointHinge";
  76837. break;
  76838. }
  76839. nativeJointData.type = type;
  76840. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76841. };
  76842. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76843. //Bug in Oimo prevents us from disposing a joint in the playground
  76844. //joint.joint.physicsJoint.dispose();
  76845. //So we will bruteforce it!
  76846. try {
  76847. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76848. }
  76849. catch (e) {
  76850. BABYLON.Tools.Warn(e);
  76851. }
  76852. };
  76853. OimoJSPlugin.prototype.isSupported = function () {
  76854. return this.BJSOIMO !== undefined;
  76855. };
  76856. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76857. if (!impostor.physicsBody.sleeping) {
  76858. //TODO check that
  76859. if (impostor.physicsBody.shapes.next) {
  76860. var parentShape = this._getLastShape(impostor.physicsBody);
  76861. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76862. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76863. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76864. }
  76865. else {
  76866. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76867. }
  76868. if (impostor.object.rotationQuaternion) {
  76869. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76870. impostor.object.rotationQuaternion.normalize();
  76871. }
  76872. }
  76873. };
  76874. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76875. var body = impostor.physicsBody;
  76876. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76877. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76878. body.syncShapes();
  76879. body.awake();
  76880. };
  76881. OimoJSPlugin.prototype._getLastShape = function (body) {
  76882. var lastShape = body.shapes;
  76883. while (lastShape.next) {
  76884. lastShape = lastShape.next;
  76885. }
  76886. return lastShape;
  76887. };
  76888. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76889. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76890. };
  76891. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76892. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76893. };
  76894. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76895. var v = impostor.physicsBody.linearVelocity;
  76896. if (!v) {
  76897. return null;
  76898. }
  76899. return new BABYLON.Vector3(v.x, v.y, v.z);
  76900. };
  76901. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76902. var v = impostor.physicsBody.angularVelocity;
  76903. if (!v) {
  76904. return null;
  76905. }
  76906. return new BABYLON.Vector3(v.x, v.y, v.z);
  76907. };
  76908. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76909. var staticBody = mass === 0;
  76910. //this will actually set the body's density and not its mass.
  76911. //But this is how oimo treats the mass variable.
  76912. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76913. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76914. };
  76915. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76916. return impostor.physicsBody.shapes.density;
  76917. };
  76918. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76919. return impostor.physicsBody.shapes.friction;
  76920. };
  76921. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76922. impostor.physicsBody.shapes.friction = friction;
  76923. };
  76924. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76925. return impostor.physicsBody.shapes.restitution;
  76926. };
  76927. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76928. impostor.physicsBody.shapes.restitution = restitution;
  76929. };
  76930. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76931. impostor.physicsBody.sleep();
  76932. };
  76933. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76934. impostor.physicsBody.awake();
  76935. };
  76936. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76937. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76938. if (minDistance !== void 0) {
  76939. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76940. }
  76941. };
  76942. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76943. //TODO separate rotational and transational motors.
  76944. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76945. if (motor) {
  76946. motor.setMotor(speed, maxForce);
  76947. }
  76948. };
  76949. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76950. //TODO separate rotational and transational motors.
  76951. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76952. if (motor) {
  76953. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76954. }
  76955. };
  76956. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76957. var body = impostor.physicsBody;
  76958. mesh.position.x = body.position.x;
  76959. mesh.position.y = body.position.y;
  76960. mesh.position.z = body.position.z;
  76961. if (mesh.rotationQuaternion) {
  76962. mesh.rotationQuaternion.x = body.orientation.x;
  76963. mesh.rotationQuaternion.y = body.orientation.y;
  76964. mesh.rotationQuaternion.z = body.orientation.z;
  76965. mesh.rotationQuaternion.w = body.orientation.s;
  76966. }
  76967. };
  76968. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76969. return impostor.physicsBody.shapes.radius;
  76970. };
  76971. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76972. var shape = impostor.physicsBody.shapes;
  76973. result.x = shape.halfWidth * 2;
  76974. result.y = shape.halfHeight * 2;
  76975. result.z = shape.halfDepth * 2;
  76976. };
  76977. OimoJSPlugin.prototype.dispose = function () {
  76978. this.world.clear();
  76979. };
  76980. return OimoJSPlugin;
  76981. }());
  76982. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76983. })(BABYLON || (BABYLON = {}));
  76984. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76985. var BABYLON;
  76986. (function (BABYLON) {
  76987. /*
  76988. * Based on jsTGALoader - Javascript loader for TGA file
  76989. * By Vincent Thibault
  76990. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76991. */
  76992. var TGATools = /** @class */ (function () {
  76993. function TGATools() {
  76994. }
  76995. TGATools.GetTGAHeader = function (data) {
  76996. var offset = 0;
  76997. var header = {
  76998. id_length: data[offset++],
  76999. colormap_type: data[offset++],
  77000. image_type: data[offset++],
  77001. colormap_index: data[offset++] | data[offset++] << 8,
  77002. colormap_length: data[offset++] | data[offset++] << 8,
  77003. colormap_size: data[offset++],
  77004. origin: [
  77005. data[offset++] | data[offset++] << 8,
  77006. data[offset++] | data[offset++] << 8
  77007. ],
  77008. width: data[offset++] | data[offset++] << 8,
  77009. height: data[offset++] | data[offset++] << 8,
  77010. pixel_size: data[offset++],
  77011. flags: data[offset++]
  77012. };
  77013. return header;
  77014. };
  77015. TGATools.UploadContent = function (gl, data) {
  77016. // Not enough data to contain header ?
  77017. if (data.length < 19) {
  77018. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77019. return;
  77020. }
  77021. // Read Header
  77022. var offset = 18;
  77023. var header = TGATools.GetTGAHeader(data);
  77024. // Assume it's a valid Targa file.
  77025. if (header.id_length + offset > data.length) {
  77026. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77027. return;
  77028. }
  77029. // Skip not needed data
  77030. offset += header.id_length;
  77031. var use_rle = false;
  77032. var use_pal = false;
  77033. var use_grey = false;
  77034. // Get some informations.
  77035. switch (header.image_type) {
  77036. case TGATools._TYPE_RLE_INDEXED:
  77037. use_rle = true;
  77038. case TGATools._TYPE_INDEXED:
  77039. use_pal = true;
  77040. break;
  77041. case TGATools._TYPE_RLE_RGB:
  77042. use_rle = true;
  77043. case TGATools._TYPE_RGB:
  77044. // use_rgb = true;
  77045. break;
  77046. case TGATools._TYPE_RLE_GREY:
  77047. use_rle = true;
  77048. case TGATools._TYPE_GREY:
  77049. use_grey = true;
  77050. break;
  77051. }
  77052. var pixel_data;
  77053. // var numAlphaBits = header.flags & 0xf;
  77054. var pixel_size = header.pixel_size >> 3;
  77055. var pixel_total = header.width * header.height * pixel_size;
  77056. // Read palettes
  77057. var palettes;
  77058. if (use_pal) {
  77059. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77060. }
  77061. // Read LRE
  77062. if (use_rle) {
  77063. pixel_data = new Uint8Array(pixel_total);
  77064. var c, count, i;
  77065. var localOffset = 0;
  77066. var pixels = new Uint8Array(pixel_size);
  77067. while (offset < pixel_total && localOffset < pixel_total) {
  77068. c = data[offset++];
  77069. count = (c & 0x7f) + 1;
  77070. // RLE pixels
  77071. if (c & 0x80) {
  77072. // Bind pixel tmp array
  77073. for (i = 0; i < pixel_size; ++i) {
  77074. pixels[i] = data[offset++];
  77075. }
  77076. // Copy pixel array
  77077. for (i = 0; i < count; ++i) {
  77078. pixel_data.set(pixels, localOffset + i * pixel_size);
  77079. }
  77080. localOffset += pixel_size * count;
  77081. }
  77082. else {
  77083. count *= pixel_size;
  77084. for (i = 0; i < count; ++i) {
  77085. pixel_data[localOffset + i] = data[offset++];
  77086. }
  77087. localOffset += count;
  77088. }
  77089. }
  77090. }
  77091. else {
  77092. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77093. }
  77094. // Load to texture
  77095. var x_start, y_start, x_step, y_step, y_end, x_end;
  77096. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77097. default:
  77098. case TGATools._ORIGIN_UL:
  77099. x_start = 0;
  77100. x_step = 1;
  77101. x_end = header.width;
  77102. y_start = 0;
  77103. y_step = 1;
  77104. y_end = header.height;
  77105. break;
  77106. case TGATools._ORIGIN_BL:
  77107. x_start = 0;
  77108. x_step = 1;
  77109. x_end = header.width;
  77110. y_start = header.height - 1;
  77111. y_step = -1;
  77112. y_end = -1;
  77113. break;
  77114. case TGATools._ORIGIN_UR:
  77115. x_start = header.width - 1;
  77116. x_step = -1;
  77117. x_end = -1;
  77118. y_start = 0;
  77119. y_step = 1;
  77120. y_end = header.height;
  77121. break;
  77122. case TGATools._ORIGIN_BR:
  77123. x_start = header.width - 1;
  77124. x_step = -1;
  77125. x_end = -1;
  77126. y_start = header.height - 1;
  77127. y_step = -1;
  77128. y_end = -1;
  77129. break;
  77130. }
  77131. // Load the specify method
  77132. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77133. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77134. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77135. };
  77136. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77137. var image = pixel_data, colormap = palettes;
  77138. var width = header.width, height = header.height;
  77139. var color, i = 0, x, y;
  77140. var imageData = new Uint8Array(width * height * 4);
  77141. for (y = y_start; y !== y_end; y += y_step) {
  77142. for (x = x_start; x !== x_end; x += x_step, i++) {
  77143. color = image[i];
  77144. imageData[(x + width * y) * 4 + 3] = 255;
  77145. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77146. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77147. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77148. }
  77149. }
  77150. return imageData;
  77151. };
  77152. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77153. var image = pixel_data;
  77154. var width = header.width, height = header.height;
  77155. var color, i = 0, x, y;
  77156. var imageData = new Uint8Array(width * height * 4);
  77157. for (y = y_start; y !== y_end; y += y_step) {
  77158. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77159. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77160. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  77161. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  77162. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  77163. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77164. }
  77165. }
  77166. return imageData;
  77167. };
  77168. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77169. var image = pixel_data;
  77170. var width = header.width, height = header.height;
  77171. var i = 0, x, y;
  77172. var imageData = new Uint8Array(width * height * 4);
  77173. for (y = y_start; y !== y_end; y += y_step) {
  77174. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77175. imageData[(x + width * y) * 4 + 3] = 255;
  77176. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77177. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77178. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77179. }
  77180. }
  77181. return imageData;
  77182. };
  77183. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77184. var image = pixel_data;
  77185. var width = header.width, height = header.height;
  77186. var i = 0, x, y;
  77187. var imageData = new Uint8Array(width * height * 4);
  77188. for (y = y_start; y !== y_end; y += y_step) {
  77189. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77190. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77191. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77192. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77193. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77194. }
  77195. }
  77196. return imageData;
  77197. };
  77198. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77199. var image = pixel_data;
  77200. var width = header.width, height = header.height;
  77201. var color, i = 0, x, y;
  77202. var imageData = new Uint8Array(width * height * 4);
  77203. for (y = y_start; y !== y_end; y += y_step) {
  77204. for (x = x_start; x !== x_end; x += x_step, i++) {
  77205. color = image[i];
  77206. imageData[(x + width * y) * 4 + 0] = color;
  77207. imageData[(x + width * y) * 4 + 1] = color;
  77208. imageData[(x + width * y) * 4 + 2] = color;
  77209. imageData[(x + width * y) * 4 + 3] = 255;
  77210. }
  77211. }
  77212. return imageData;
  77213. };
  77214. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77215. var image = pixel_data;
  77216. var width = header.width, height = header.height;
  77217. var i = 0, x, y;
  77218. var imageData = new Uint8Array(width * height * 4);
  77219. for (y = y_start; y !== y_end; y += y_step) {
  77220. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77221. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77222. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77223. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77224. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77225. }
  77226. }
  77227. return imageData;
  77228. };
  77229. //private static _TYPE_NO_DATA = 0;
  77230. TGATools._TYPE_INDEXED = 1;
  77231. TGATools._TYPE_RGB = 2;
  77232. TGATools._TYPE_GREY = 3;
  77233. TGATools._TYPE_RLE_INDEXED = 9;
  77234. TGATools._TYPE_RLE_RGB = 10;
  77235. TGATools._TYPE_RLE_GREY = 11;
  77236. TGATools._ORIGIN_MASK = 0x30;
  77237. TGATools._ORIGIN_SHIFT = 0x04;
  77238. TGATools._ORIGIN_BL = 0x00;
  77239. TGATools._ORIGIN_BR = 0x01;
  77240. TGATools._ORIGIN_UL = 0x02;
  77241. TGATools._ORIGIN_UR = 0x03;
  77242. return TGATools;
  77243. }());
  77244. BABYLON.TGATools = TGATools;
  77245. })(BABYLON || (BABYLON = {}));
  77246. //# sourceMappingURL=babylon.tga.js.map
  77247. var BABYLON;
  77248. (function (BABYLON) {
  77249. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77250. // All values and structures referenced from:
  77251. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77252. var DDS_MAGIC = 0x20534444;
  77253. var
  77254. //DDSD_CAPS = 0x1,
  77255. //DDSD_HEIGHT = 0x2,
  77256. //DDSD_WIDTH = 0x4,
  77257. //DDSD_PITCH = 0x8,
  77258. //DDSD_PIXELFORMAT = 0x1000,
  77259. DDSD_MIPMAPCOUNT = 0x20000;
  77260. //DDSD_LINEARSIZE = 0x80000,
  77261. //DDSD_DEPTH = 0x800000;
  77262. // var DDSCAPS_COMPLEX = 0x8,
  77263. // DDSCAPS_MIPMAP = 0x400000,
  77264. // DDSCAPS_TEXTURE = 0x1000;
  77265. var DDSCAPS2_CUBEMAP = 0x200;
  77266. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77267. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77268. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77269. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77270. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77271. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77272. // DDSCAPS2_VOLUME = 0x200000;
  77273. var
  77274. //DDPF_ALPHAPIXELS = 0x1,
  77275. //DDPF_ALPHA = 0x2,
  77276. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77277. //DDPF_YUV = 0x200,
  77278. DDPF_LUMINANCE = 0x20000;
  77279. function FourCCToInt32(value) {
  77280. return value.charCodeAt(0) +
  77281. (value.charCodeAt(1) << 8) +
  77282. (value.charCodeAt(2) << 16) +
  77283. (value.charCodeAt(3) << 24);
  77284. }
  77285. function Int32ToFourCC(value) {
  77286. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77287. }
  77288. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77289. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77290. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77291. var FOURCC_DX10 = FourCCToInt32("DX10");
  77292. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77293. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77294. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77295. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77296. var headerLengthInt = 31; // The header length in 32 bit ints
  77297. // Offsets into the header array
  77298. var off_magic = 0;
  77299. var off_size = 1;
  77300. var off_flags = 2;
  77301. var off_height = 3;
  77302. var off_width = 4;
  77303. var off_mipmapCount = 7;
  77304. var off_pfFlags = 20;
  77305. var off_pfFourCC = 21;
  77306. var off_RGBbpp = 22;
  77307. var off_RMask = 23;
  77308. var off_GMask = 24;
  77309. var off_BMask = 25;
  77310. var off_AMask = 26;
  77311. // var off_caps1 = 27;
  77312. var off_caps2 = 28;
  77313. // var off_caps3 = 29;
  77314. // var off_caps4 = 30;
  77315. var off_dxgiFormat = 32;
  77316. ;
  77317. var DDSTools = /** @class */ (function () {
  77318. function DDSTools() {
  77319. }
  77320. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77321. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77322. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77323. var mipmapCount = 1;
  77324. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77325. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77326. }
  77327. var fourCC = header[off_pfFourCC];
  77328. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77329. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77330. switch (fourCC) {
  77331. case FOURCC_D3DFMT_R16G16B16A16F:
  77332. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77333. break;
  77334. case FOURCC_D3DFMT_R32G32B32A32F:
  77335. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77336. break;
  77337. case FOURCC_DX10:
  77338. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77339. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77340. break;
  77341. }
  77342. }
  77343. return {
  77344. width: header[off_width],
  77345. height: header[off_height],
  77346. mipmapCount: mipmapCount,
  77347. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77348. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77349. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77350. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77351. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77352. dxgiFormat: dxgiFormat,
  77353. textureType: textureType
  77354. };
  77355. };
  77356. DDSTools._ToHalfFloat = function (value) {
  77357. if (!DDSTools._FloatView) {
  77358. DDSTools._FloatView = new Float32Array(1);
  77359. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77360. }
  77361. DDSTools._FloatView[0] = value;
  77362. var x = DDSTools._Int32View[0];
  77363. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77364. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77365. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77366. /* If zero, or denormal, or exponent underflows too much for a denormal
  77367. * half, return signed zero. */
  77368. if (e < 103) {
  77369. return bits;
  77370. }
  77371. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77372. if (e > 142) {
  77373. bits |= 0x7c00;
  77374. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77375. * not Inf, so make sure we set one mantissa bit too. */
  77376. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77377. return bits;
  77378. }
  77379. /* If exponent underflows but not too much, return a denormal */
  77380. if (e < 113) {
  77381. m |= 0x0800;
  77382. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77383. * to 1, which is OK. */
  77384. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77385. return bits;
  77386. }
  77387. bits |= ((e - 112) << 10) | (m >> 1);
  77388. bits += m & 1;
  77389. return bits;
  77390. };
  77391. DDSTools._FromHalfFloat = function (value) {
  77392. var s = (value & 0x8000) >> 15;
  77393. var e = (value & 0x7C00) >> 10;
  77394. var f = value & 0x03FF;
  77395. if (e === 0) {
  77396. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77397. }
  77398. else if (e == 0x1F) {
  77399. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77400. }
  77401. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77402. };
  77403. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77404. var destArray = new Float32Array(dataLength);
  77405. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77406. var index = 0;
  77407. for (var y = 0; y < height; y++) {
  77408. for (var x = 0; x < width; x++) {
  77409. var srcPos = (x + y * width) * 4;
  77410. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77411. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77412. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77413. if (DDSTools.StoreLODInAlphaChannel) {
  77414. destArray[index + 3] = lod;
  77415. }
  77416. else {
  77417. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77418. }
  77419. index += 4;
  77420. }
  77421. }
  77422. return destArray;
  77423. };
  77424. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77425. if (DDSTools.StoreLODInAlphaChannel) {
  77426. var destArray = new Uint16Array(dataLength);
  77427. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77428. var index = 0;
  77429. for (var y = 0; y < height; y++) {
  77430. for (var x = 0; x < width; x++) {
  77431. var srcPos = (x + y * width) * 4;
  77432. destArray[index] = srcData[srcPos];
  77433. destArray[index + 1] = srcData[srcPos + 1];
  77434. destArray[index + 2] = srcData[srcPos + 2];
  77435. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77436. index += 4;
  77437. }
  77438. }
  77439. return destArray;
  77440. }
  77441. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77442. };
  77443. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77444. if (DDSTools.StoreLODInAlphaChannel) {
  77445. var destArray = new Float32Array(dataLength);
  77446. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77447. var index = 0;
  77448. for (var y = 0; y < height; y++) {
  77449. for (var x = 0; x < width; x++) {
  77450. var srcPos = (x + y * width) * 4;
  77451. destArray[index] = srcData[srcPos];
  77452. destArray[index + 1] = srcData[srcPos + 1];
  77453. destArray[index + 2] = srcData[srcPos + 2];
  77454. destArray[index + 3] = lod;
  77455. index += 4;
  77456. }
  77457. }
  77458. return destArray;
  77459. }
  77460. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77461. };
  77462. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77463. var destArray = new Uint8Array(dataLength);
  77464. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77465. var index = 0;
  77466. for (var y = 0; y < height; y++) {
  77467. for (var x = 0; x < width; x++) {
  77468. var srcPos = (x + y * width) * 4;
  77469. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77470. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77471. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77472. if (DDSTools.StoreLODInAlphaChannel) {
  77473. destArray[index + 3] = lod;
  77474. }
  77475. else {
  77476. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77477. }
  77478. index += 4;
  77479. }
  77480. }
  77481. return destArray;
  77482. };
  77483. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77484. var destArray = new Uint8Array(dataLength);
  77485. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77486. var index = 0;
  77487. for (var y = 0; y < height; y++) {
  77488. for (var x = 0; x < width; x++) {
  77489. var srcPos = (x + y * width) * 4;
  77490. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77491. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77492. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77493. if (DDSTools.StoreLODInAlphaChannel) {
  77494. destArray[index + 3] = lod;
  77495. }
  77496. else {
  77497. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77498. }
  77499. index += 4;
  77500. }
  77501. }
  77502. return destArray;
  77503. };
  77504. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77505. var byteArray = new Uint8Array(dataLength);
  77506. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77507. var index = 0;
  77508. for (var y = 0; y < height; y++) {
  77509. for (var x = 0; x < width; x++) {
  77510. var srcPos = (x + y * width) * 4;
  77511. byteArray[index] = srcData[srcPos + rOffset];
  77512. byteArray[index + 1] = srcData[srcPos + gOffset];
  77513. byteArray[index + 2] = srcData[srcPos + bOffset];
  77514. byteArray[index + 3] = srcData[srcPos + aOffset];
  77515. index += 4;
  77516. }
  77517. }
  77518. return byteArray;
  77519. };
  77520. DDSTools._ExtractLongWordOrder = function (value) {
  77521. if (value === 0 || value === 255 || value === -16777216) {
  77522. return 0;
  77523. }
  77524. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77525. };
  77526. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77527. var byteArray = new Uint8Array(dataLength);
  77528. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77529. var index = 0;
  77530. for (var y = 0; y < height; y++) {
  77531. for (var x = 0; x < width; x++) {
  77532. var srcPos = (x + y * width) * 3;
  77533. byteArray[index] = srcData[srcPos + rOffset];
  77534. byteArray[index + 1] = srcData[srcPos + gOffset];
  77535. byteArray[index + 2] = srcData[srcPos + bOffset];
  77536. index += 3;
  77537. }
  77538. }
  77539. return byteArray;
  77540. };
  77541. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77542. var byteArray = new Uint8Array(dataLength);
  77543. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77544. var index = 0;
  77545. for (var y = 0; y < height; y++) {
  77546. for (var x = 0; x < width; x++) {
  77547. var srcPos = (x + y * width);
  77548. byteArray[index] = srcData[srcPos];
  77549. index++;
  77550. }
  77551. }
  77552. return byteArray;
  77553. };
  77554. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77555. if (lodIndex === void 0) { lodIndex = -1; }
  77556. var ext = engine.getCaps().s3tc;
  77557. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77558. var fourCC, width, height, dataLength = 0, dataOffset;
  77559. var byteArray, mipmapCount, mip;
  77560. var internalFormat = 0;
  77561. var format = 0;
  77562. var blockBytes = 1;
  77563. if (header[off_magic] !== DDS_MAGIC) {
  77564. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77565. return;
  77566. }
  77567. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77568. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77569. return;
  77570. }
  77571. if (info.isCompressed && !ext) {
  77572. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77573. return;
  77574. }
  77575. var bpp = header[off_RGBbpp];
  77576. dataOffset = header[off_size] + 4;
  77577. var computeFormats = false;
  77578. if (info.isFourCC) {
  77579. fourCC = header[off_pfFourCC];
  77580. switch (fourCC) {
  77581. case FOURCC_DXT1:
  77582. blockBytes = 8;
  77583. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77584. break;
  77585. case FOURCC_DXT3:
  77586. blockBytes = 16;
  77587. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77588. break;
  77589. case FOURCC_DXT5:
  77590. blockBytes = 16;
  77591. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77592. break;
  77593. case FOURCC_D3DFMT_R16G16B16A16F:
  77594. computeFormats = true;
  77595. break;
  77596. case FOURCC_D3DFMT_R32G32B32A32F:
  77597. computeFormats = true;
  77598. break;
  77599. case FOURCC_DX10:
  77600. // There is an additionnal header so dataOffset need to be changed
  77601. dataOffset += 5 * 4; // 5 uints
  77602. var supported = false;
  77603. switch (info.dxgiFormat) {
  77604. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77605. computeFormats = true;
  77606. supported = true;
  77607. break;
  77608. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77609. info.isRGB = true;
  77610. info.isFourCC = false;
  77611. bpp = 32;
  77612. supported = true;
  77613. break;
  77614. }
  77615. if (supported) {
  77616. break;
  77617. }
  77618. default:
  77619. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77620. return;
  77621. }
  77622. }
  77623. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77624. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77625. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77626. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77627. if (computeFormats) {
  77628. format = engine._getWebGLTextureType(info.textureType);
  77629. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77630. }
  77631. mipmapCount = 1;
  77632. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77633. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77634. }
  77635. for (var face = 0; face < faces; face++) {
  77636. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77637. width = header[off_width];
  77638. height = header[off_height];
  77639. for (mip = 0; mip < mipmapCount; ++mip) {
  77640. if (lodIndex === -1 || lodIndex === mip) {
  77641. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77642. var i = (lodIndex === -1) ? mip : 0;
  77643. if (!info.isCompressed && info.isFourCC) {
  77644. dataLength = width * height * 4;
  77645. var floatArray = null;
  77646. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77647. if (bpp === 128) {
  77648. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77649. }
  77650. else if (bpp === 64) {
  77651. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77652. }
  77653. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77654. format = engine._getWebGLTextureType(info.textureType);
  77655. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77656. }
  77657. else {
  77658. if (bpp === 128) {
  77659. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77660. }
  77661. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77662. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77663. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77664. format = engine._getWebGLTextureType(info.textureType);
  77665. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77666. }
  77667. else {
  77668. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77669. }
  77670. }
  77671. if (floatArray) {
  77672. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77673. }
  77674. }
  77675. else if (info.isRGB) {
  77676. if (bpp === 24) {
  77677. dataLength = width * height * 3;
  77678. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77679. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77680. }
  77681. else {
  77682. dataLength = width * height * 4;
  77683. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77684. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77685. }
  77686. }
  77687. else if (info.isLuminance) {
  77688. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77689. var unpaddedRowSize = width;
  77690. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77691. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77692. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77693. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77694. }
  77695. else {
  77696. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77697. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77698. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77699. }
  77700. }
  77701. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77702. width *= 0.5;
  77703. height *= 0.5;
  77704. width = Math.max(1.0, width);
  77705. height = Math.max(1.0, height);
  77706. }
  77707. if (currentFace !== undefined) {
  77708. // Loading a single face
  77709. break;
  77710. }
  77711. }
  77712. };
  77713. DDSTools.StoreLODInAlphaChannel = false;
  77714. return DDSTools;
  77715. }());
  77716. BABYLON.DDSTools = DDSTools;
  77717. })(BABYLON || (BABYLON = {}));
  77718. //# sourceMappingURL=babylon.dds.js.map
  77719. var BABYLON;
  77720. (function (BABYLON) {
  77721. /**
  77722. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77723. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77724. */
  77725. var KhronosTextureContainer = /** @class */ (function () {
  77726. /**
  77727. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77728. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77729. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77730. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77731. */
  77732. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77733. this.arrayBuffer = arrayBuffer;
  77734. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77735. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77736. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77737. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77738. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77739. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77740. BABYLON.Tools.Error("texture missing KTX identifier");
  77741. return;
  77742. }
  77743. // load the reset of the header in native 32 bit int
  77744. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77745. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77746. var oppositeEndianess = header[0] === 0x01020304;
  77747. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77748. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77749. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77750. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77751. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77752. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77753. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77754. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77755. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77756. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77757. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77758. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77759. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77760. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77761. if (this.glType !== 0) {
  77762. BABYLON.Tools.Error("only compressed formats currently supported");
  77763. return;
  77764. }
  77765. else {
  77766. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77767. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77768. }
  77769. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77770. BABYLON.Tools.Error("only 2D textures currently supported");
  77771. return;
  77772. }
  77773. if (this.numberOfArrayElements !== 0) {
  77774. BABYLON.Tools.Error("texture arrays not currently supported");
  77775. return;
  77776. }
  77777. if (this.numberOfFaces !== facesExpected) {
  77778. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77779. return;
  77780. }
  77781. // we now have a completely validated file, so could use existence of loadType as success
  77782. // would need to make this more elaborate & adjust checks above to support more than one load type
  77783. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77784. }
  77785. // not as fast hardware based, but will probably never need to use
  77786. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77787. return ((val & 0xFF) << 24)
  77788. | ((val & 0xFF00) << 8)
  77789. | ((val >> 8) & 0xFF00)
  77790. | ((val >> 24) & 0xFF);
  77791. };
  77792. /**
  77793. * It is assumed that the texture has already been created & is currently bound
  77794. */
  77795. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77796. switch (this.loadType) {
  77797. case KhronosTextureContainer.COMPRESSED_2D:
  77798. this._upload2DCompressedLevels(gl, loadMipmaps);
  77799. break;
  77800. case KhronosTextureContainer.TEX_2D:
  77801. case KhronosTextureContainer.COMPRESSED_3D:
  77802. case KhronosTextureContainer.TEX_3D:
  77803. }
  77804. };
  77805. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77806. // initialize width & height for level 1
  77807. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77808. var width = this.pixelWidth;
  77809. var height = this.pixelHeight;
  77810. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77811. for (var level = 0; level < mipmapCount; level++) {
  77812. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77813. for (var face = 0; face < this.numberOfFaces; face++) {
  77814. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77815. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77816. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77817. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77818. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77819. }
  77820. width = Math.max(1.0, width * 0.5);
  77821. height = Math.max(1.0, height * 0.5);
  77822. }
  77823. };
  77824. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77825. // load types
  77826. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77827. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77828. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77829. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77830. return KhronosTextureContainer;
  77831. }());
  77832. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77833. })(BABYLON || (BABYLON = {}));
  77834. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77835. var BABYLON;
  77836. (function (BABYLON) {
  77837. var Debug = /** @class */ (function () {
  77838. function Debug() {
  77839. }
  77840. Debug.AxesViewer = /** @class */ (function () {
  77841. function AxesViewer(scene, scaleLines) {
  77842. if (scaleLines === void 0) { scaleLines = 1; }
  77843. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77844. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77845. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77846. this.scaleLines = 1;
  77847. this.scaleLines = scaleLines;
  77848. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77849. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77850. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77851. this._xmesh.renderingGroupId = 2;
  77852. this._ymesh.renderingGroupId = 2;
  77853. this._zmesh.renderingGroupId = 2;
  77854. this._xmesh.material.checkReadyOnlyOnce = true;
  77855. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77856. this._ymesh.material.checkReadyOnlyOnce = true;
  77857. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77858. this._zmesh.material.checkReadyOnlyOnce = true;
  77859. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77860. this.scene = scene;
  77861. }
  77862. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77863. var scaleLines = this.scaleLines;
  77864. if (this._xmesh) {
  77865. this._xmesh.position.copyFrom(position);
  77866. }
  77867. if (this._ymesh) {
  77868. this._ymesh.position.copyFrom(position);
  77869. }
  77870. if (this._zmesh) {
  77871. this._zmesh.position.copyFrom(position);
  77872. }
  77873. var point2 = this._xline[1];
  77874. point2.x = xaxis.x * scaleLines;
  77875. point2.y = xaxis.y * scaleLines;
  77876. point2.z = xaxis.z * scaleLines;
  77877. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77878. point2 = this._yline[1];
  77879. point2.x = yaxis.x * scaleLines;
  77880. point2.y = yaxis.y * scaleLines;
  77881. point2.z = yaxis.z * scaleLines;
  77882. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77883. point2 = this._zline[1];
  77884. point2.x = zaxis.x * scaleLines;
  77885. point2.y = zaxis.y * scaleLines;
  77886. point2.z = zaxis.z * scaleLines;
  77887. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77888. };
  77889. AxesViewer.prototype.dispose = function () {
  77890. if (this._xmesh) {
  77891. this._xmesh.dispose();
  77892. }
  77893. if (this._ymesh) {
  77894. this._ymesh.dispose();
  77895. }
  77896. if (this._zmesh) {
  77897. this._zmesh.dispose();
  77898. }
  77899. this._xmesh = null;
  77900. this._ymesh = null;
  77901. this._zmesh = null;
  77902. this.scene = null;
  77903. };
  77904. return AxesViewer;
  77905. }());
  77906. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77907. __extends(BoneAxesViewer, _super);
  77908. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77909. if (scaleLines === void 0) { scaleLines = 1; }
  77910. var _this = _super.call(this, scene, scaleLines) || this;
  77911. _this.pos = BABYLON.Vector3.Zero();
  77912. _this.xaxis = BABYLON.Vector3.Zero();
  77913. _this.yaxis = BABYLON.Vector3.Zero();
  77914. _this.zaxis = BABYLON.Vector3.Zero();
  77915. _this.mesh = mesh;
  77916. _this.bone = bone;
  77917. return _this;
  77918. }
  77919. BoneAxesViewer.prototype.update = function () {
  77920. if (!this.mesh || !this.bone) {
  77921. return;
  77922. }
  77923. var bone = this.bone;
  77924. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77925. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77926. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77927. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77928. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77929. };
  77930. BoneAxesViewer.prototype.dispose = function () {
  77931. if (this.mesh) {
  77932. this.mesh = null;
  77933. this.bone = null;
  77934. _super.prototype.dispose.call(this);
  77935. }
  77936. };
  77937. return BoneAxesViewer;
  77938. }(Debug.AxesViewer));
  77939. Debug.PhysicsViewer = /** @class */ (function () {
  77940. function PhysicsViewer(scene) {
  77941. this._impostors = [];
  77942. this._meshes = [];
  77943. this._numMeshes = 0;
  77944. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77945. var physicEngine = this._scene.getPhysicsEngine();
  77946. if (physicEngine) {
  77947. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77948. }
  77949. }
  77950. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77951. var plugin = this._physicsEnginePlugin;
  77952. for (var i = 0; i < this._numMeshes; i++) {
  77953. var impostor = this._impostors[i];
  77954. if (!impostor) {
  77955. continue;
  77956. }
  77957. if (impostor.isDisposed) {
  77958. this.hideImpostor(this._impostors[i--]);
  77959. }
  77960. else {
  77961. var mesh = this._meshes[i];
  77962. if (mesh && plugin) {
  77963. plugin.syncMeshWithImpostor(mesh, impostor);
  77964. }
  77965. }
  77966. }
  77967. };
  77968. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77969. if (!this._scene) {
  77970. return;
  77971. }
  77972. for (var i = 0; i < this._numMeshes; i++) {
  77973. if (this._impostors[i] == impostor) {
  77974. return;
  77975. }
  77976. }
  77977. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77978. if (debugMesh) {
  77979. this._impostors[this._numMeshes] = impostor;
  77980. this._meshes[this._numMeshes] = debugMesh;
  77981. if (this._numMeshes === 0) {
  77982. this._renderFunction = this._updateDebugMeshes.bind(this);
  77983. this._scene.registerBeforeRender(this._renderFunction);
  77984. }
  77985. this._numMeshes++;
  77986. }
  77987. };
  77988. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77989. if (!impostor || !this._scene) {
  77990. return;
  77991. }
  77992. var removed = false;
  77993. for (var i = 0; i < this._numMeshes; i++) {
  77994. if (this._impostors[i] == impostor) {
  77995. var mesh = this._meshes[i];
  77996. if (!mesh) {
  77997. continue;
  77998. }
  77999. this._scene.removeMesh(mesh);
  78000. mesh.dispose();
  78001. this._numMeshes--;
  78002. if (this._numMeshes > 0) {
  78003. this._meshes[i] = this._meshes[this._numMeshes];
  78004. this._impostors[i] = this._impostors[this._numMeshes];
  78005. this._meshes[this._numMeshes] = null;
  78006. this._impostors[this._numMeshes] = null;
  78007. }
  78008. else {
  78009. this._meshes[0] = null;
  78010. this._impostors[0] = null;
  78011. }
  78012. removed = true;
  78013. break;
  78014. }
  78015. }
  78016. if (removed && this._numMeshes === 0) {
  78017. this._scene.unregisterBeforeRender(this._renderFunction);
  78018. }
  78019. };
  78020. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78021. if (!this._debugMaterial) {
  78022. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78023. this._debugMaterial.wireframe = true;
  78024. }
  78025. return this._debugMaterial;
  78026. };
  78027. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78028. if (!this._debugBoxMesh) {
  78029. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78030. this._debugBoxMesh.renderingGroupId = 1;
  78031. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78032. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78033. scene.removeMesh(this._debugBoxMesh);
  78034. }
  78035. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78036. };
  78037. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78038. if (!this._debugSphereMesh) {
  78039. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78040. this._debugSphereMesh.renderingGroupId = 1;
  78041. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78042. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78043. scene.removeMesh(this._debugSphereMesh);
  78044. }
  78045. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78046. };
  78047. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78048. var mesh = null;
  78049. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78050. mesh = this._getDebugBoxMesh(scene);
  78051. impostor.getBoxSizeToRef(mesh.scaling);
  78052. }
  78053. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78054. mesh = this._getDebugSphereMesh(scene);
  78055. var radius = impostor.getRadius();
  78056. mesh.scaling.x = radius * 2;
  78057. mesh.scaling.y = radius * 2;
  78058. mesh.scaling.z = radius * 2;
  78059. }
  78060. return mesh;
  78061. };
  78062. PhysicsViewer.prototype.dispose = function () {
  78063. for (var i = 0; i < this._numMeshes; i++) {
  78064. this.hideImpostor(this._impostors[i]);
  78065. }
  78066. if (this._debugBoxMesh) {
  78067. this._debugBoxMesh.dispose();
  78068. }
  78069. if (this._debugSphereMesh) {
  78070. this._debugSphereMesh.dispose();
  78071. }
  78072. if (this._debugMaterial) {
  78073. this._debugMaterial.dispose();
  78074. }
  78075. this._impostors.length = 0;
  78076. this._scene = null;
  78077. this._physicsEnginePlugin = null;
  78078. };
  78079. return PhysicsViewer;
  78080. }());
  78081. Debug.SkeletonViewer = /** @class */ (function () {
  78082. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78083. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78084. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78085. this.skeleton = skeleton;
  78086. this.mesh = mesh;
  78087. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78088. this.renderingGroupId = renderingGroupId;
  78089. this.color = BABYLON.Color3.White();
  78090. this._debugLines = new Array();
  78091. this._isEnabled = false;
  78092. this._scene = scene;
  78093. this.update();
  78094. this._renderFunction = this.update.bind(this);
  78095. }
  78096. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78097. get: function () {
  78098. return this._isEnabled;
  78099. },
  78100. set: function (value) {
  78101. if (this._isEnabled === value) {
  78102. return;
  78103. }
  78104. this._isEnabled = value;
  78105. if (value) {
  78106. this._scene.registerBeforeRender(this._renderFunction);
  78107. }
  78108. else {
  78109. this._scene.unregisterBeforeRender(this._renderFunction);
  78110. }
  78111. },
  78112. enumerable: true,
  78113. configurable: true
  78114. });
  78115. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78116. if (x === void 0) { x = 0; }
  78117. if (y === void 0) { y = 0; }
  78118. if (z === void 0) { z = 0; }
  78119. var tmat = BABYLON.Tmp.Matrix[0];
  78120. var parentBone = bone.getParent();
  78121. tmat.copyFrom(bone.getLocalMatrix());
  78122. if (x !== 0 || y !== 0 || z !== 0) {
  78123. var tmat2 = BABYLON.Tmp.Matrix[1];
  78124. BABYLON.Matrix.IdentityToRef(tmat2);
  78125. tmat2.m[12] = x;
  78126. tmat2.m[13] = y;
  78127. tmat2.m[14] = z;
  78128. tmat2.multiplyToRef(tmat, tmat);
  78129. }
  78130. if (parentBone) {
  78131. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78132. }
  78133. tmat.multiplyToRef(meshMat, tmat);
  78134. position.x = tmat.m[12];
  78135. position.y = tmat.m[13];
  78136. position.z = tmat.m[14];
  78137. };
  78138. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78139. var len = bones.length;
  78140. var meshPos = this.mesh.position;
  78141. for (var i = 0; i < len; i++) {
  78142. var bone = bones[i];
  78143. var points = this._debugLines[i];
  78144. if (!points) {
  78145. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78146. this._debugLines[i] = points;
  78147. }
  78148. this._getBonePosition(points[0], bone, meshMat);
  78149. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78150. points[0].subtractInPlace(meshPos);
  78151. points[1].subtractInPlace(meshPos);
  78152. }
  78153. };
  78154. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78155. var len = bones.length;
  78156. var boneNum = 0;
  78157. var meshPos = this.mesh.position;
  78158. for (var i = len - 1; i >= 0; i--) {
  78159. var childBone = bones[i];
  78160. var parentBone = childBone.getParent();
  78161. if (!parentBone) {
  78162. continue;
  78163. }
  78164. var points = this._debugLines[boneNum];
  78165. if (!points) {
  78166. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78167. this._debugLines[boneNum] = points;
  78168. }
  78169. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78170. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78171. points[0].subtractInPlace(meshPos);
  78172. points[1].subtractInPlace(meshPos);
  78173. boneNum++;
  78174. }
  78175. };
  78176. SkeletonViewer.prototype.update = function () {
  78177. if (this.autoUpdateBonesMatrices) {
  78178. this.skeleton.computeAbsoluteTransforms();
  78179. }
  78180. if (this.skeleton.bones[0].length === undefined) {
  78181. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78182. }
  78183. else {
  78184. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78185. }
  78186. if (!this._debugMesh) {
  78187. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78188. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78189. }
  78190. else {
  78191. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78192. }
  78193. this._debugMesh.position.copyFrom(this.mesh.position);
  78194. this._debugMesh.color = this.color;
  78195. };
  78196. SkeletonViewer.prototype.dispose = function () {
  78197. if (this._debugMesh) {
  78198. this.isEnabled = false;
  78199. this._debugMesh.dispose();
  78200. this._debugMesh = null;
  78201. }
  78202. };
  78203. return SkeletonViewer;
  78204. }());
  78205. return Debug;
  78206. }());
  78207. BABYLON.Debug = Debug;
  78208. })(BABYLON || (BABYLON = {}));
  78209. //# sourceMappingURL=babylon.debugModules.js.map
  78210. var BABYLON;
  78211. (function (BABYLON) {
  78212. var RayHelper = /** @class */ (function () {
  78213. function RayHelper(ray) {
  78214. this.ray = ray;
  78215. }
  78216. RayHelper.CreateAndShow = function (ray, scene, color) {
  78217. var helper = new RayHelper(ray);
  78218. helper.show(scene, color);
  78219. return helper;
  78220. };
  78221. RayHelper.prototype.show = function (scene, color) {
  78222. if (!this._renderFunction && this.ray) {
  78223. var ray = this.ray;
  78224. this._renderFunction = this._render.bind(this);
  78225. this._scene = scene;
  78226. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78227. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78228. if (this._renderFunction) {
  78229. this._scene.registerBeforeRender(this._renderFunction);
  78230. }
  78231. }
  78232. if (color && this._renderLine) {
  78233. this._renderLine.color.copyFrom(color);
  78234. }
  78235. };
  78236. RayHelper.prototype.hide = function () {
  78237. if (this._renderFunction && this._scene) {
  78238. this._scene.unregisterBeforeRender(this._renderFunction);
  78239. this._scene = null;
  78240. this._renderFunction = null;
  78241. if (this._renderLine) {
  78242. this._renderLine.dispose();
  78243. this._renderLine = null;
  78244. }
  78245. this._renderPoints = [];
  78246. }
  78247. };
  78248. RayHelper.prototype._render = function () {
  78249. var ray = this.ray;
  78250. if (!ray) {
  78251. return;
  78252. }
  78253. var point = this._renderPoints[1];
  78254. var len = Math.min(ray.length, 1000000);
  78255. point.copyFrom(ray.direction);
  78256. point.scaleInPlace(len);
  78257. point.addInPlace(ray.origin);
  78258. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78259. };
  78260. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78261. this._attachedToMesh = mesh;
  78262. var ray = this.ray;
  78263. if (!ray) {
  78264. return;
  78265. }
  78266. if (!ray.direction) {
  78267. ray.direction = BABYLON.Vector3.Zero();
  78268. }
  78269. if (!ray.origin) {
  78270. ray.origin = BABYLON.Vector3.Zero();
  78271. }
  78272. if (length) {
  78273. ray.length = length;
  78274. }
  78275. if (!meshSpaceOrigin) {
  78276. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78277. }
  78278. if (!meshSpaceDirection) {
  78279. // -1 so that this will work with Mesh.lookAt
  78280. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78281. }
  78282. if (!this._meshSpaceDirection) {
  78283. this._meshSpaceDirection = meshSpaceDirection.clone();
  78284. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78285. }
  78286. else {
  78287. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78288. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78289. }
  78290. if (!this._updateToMeshFunction) {
  78291. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78292. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78293. }
  78294. this._updateToMesh();
  78295. };
  78296. RayHelper.prototype.detachFromMesh = function () {
  78297. if (this._attachedToMesh) {
  78298. if (this._updateToMeshFunction) {
  78299. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78300. }
  78301. this._attachedToMesh = null;
  78302. this._updateToMeshFunction = null;
  78303. }
  78304. };
  78305. RayHelper.prototype._updateToMesh = function () {
  78306. var ray = this.ray;
  78307. if (!this._attachedToMesh || !ray) {
  78308. return;
  78309. }
  78310. if (this._attachedToMesh._isDisposed) {
  78311. this.detachFromMesh();
  78312. return;
  78313. }
  78314. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78315. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78316. };
  78317. RayHelper.prototype.dispose = function () {
  78318. this.hide();
  78319. this.detachFromMesh();
  78320. this.ray = null;
  78321. };
  78322. return RayHelper;
  78323. }());
  78324. BABYLON.RayHelper = RayHelper;
  78325. })(BABYLON || (BABYLON = {}));
  78326. //# sourceMappingURL=babylon.rayHelper.js.map
  78327. var BABYLON;
  78328. (function (BABYLON) {
  78329. // load the inspector using require, if not present in the global namespace.
  78330. var DebugLayer = /** @class */ (function () {
  78331. function DebugLayer(scene) {
  78332. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78333. this._scene = scene;
  78334. // load inspector using require, if it doesn't exist on the global namespace.
  78335. }
  78336. /** Creates the inspector window. */
  78337. DebugLayer.prototype._createInspector = function (config) {
  78338. if (config === void 0) { config = {}; }
  78339. var popup = config.popup || false;
  78340. var initialTab = config.initialTab || 0;
  78341. var parentElement = config.parentElement || null;
  78342. if (!this._inspector) {
  78343. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78344. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78345. } // else nothing to do,; instance is already existing
  78346. };
  78347. DebugLayer.prototype.isVisible = function () {
  78348. if (!this._inspector) {
  78349. return false;
  78350. }
  78351. return true;
  78352. };
  78353. DebugLayer.prototype.hide = function () {
  78354. if (this._inspector) {
  78355. try {
  78356. this._inspector.dispose();
  78357. }
  78358. catch (e) {
  78359. // If the inspector has been removed directly from the inspector tool
  78360. }
  78361. this._inspector = null;
  78362. }
  78363. };
  78364. DebugLayer.prototype.show = function (config) {
  78365. if (config === void 0) { config = {}; }
  78366. if (typeof this.BJSINSPECTOR == 'undefined') {
  78367. // Load inspector and add it to the DOM
  78368. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78369. }
  78370. else {
  78371. // Otherwise creates the inspector
  78372. this._createInspector(config);
  78373. }
  78374. };
  78375. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78376. return DebugLayer;
  78377. }());
  78378. BABYLON.DebugLayer = DebugLayer;
  78379. })(BABYLON || (BABYLON = {}));
  78380. //# sourceMappingURL=babylon.debugLayer.js.map
  78381. var BABYLON;
  78382. (function (BABYLON) {
  78383. var BoundingBoxRenderer = /** @class */ (function () {
  78384. function BoundingBoxRenderer(scene) {
  78385. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78386. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78387. this.showBackLines = true;
  78388. this.renderList = new BABYLON.SmartArray(32);
  78389. this._vertexBuffers = {};
  78390. this._scene = scene;
  78391. }
  78392. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78393. if (this._colorShader) {
  78394. return;
  78395. }
  78396. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78397. attributes: [BABYLON.VertexBuffer.PositionKind],
  78398. uniforms: ["world", "viewProjection", "color"]
  78399. });
  78400. var engine = this._scene.getEngine();
  78401. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78402. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78403. this._createIndexBuffer();
  78404. };
  78405. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78406. var engine = this._scene.getEngine();
  78407. 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]);
  78408. };
  78409. BoundingBoxRenderer.prototype._rebuild = function () {
  78410. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78411. if (vb) {
  78412. vb._rebuild();
  78413. }
  78414. this._createIndexBuffer();
  78415. };
  78416. BoundingBoxRenderer.prototype.reset = function () {
  78417. this.renderList.reset();
  78418. };
  78419. BoundingBoxRenderer.prototype.render = function () {
  78420. if (this.renderList.length === 0) {
  78421. return;
  78422. }
  78423. this._prepareRessources();
  78424. if (!this._colorShader.isReady()) {
  78425. return;
  78426. }
  78427. var engine = this._scene.getEngine();
  78428. engine.setDepthWrite(false);
  78429. this._colorShader._preBind();
  78430. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78431. var boundingBox = this.renderList.data[boundingBoxIndex];
  78432. var min = boundingBox.minimum;
  78433. var max = boundingBox.maximum;
  78434. var diff = max.subtract(min);
  78435. var median = min.add(diff.scale(0.5));
  78436. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78437. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78438. .multiply(boundingBox.getWorldMatrix());
  78439. // VBOs
  78440. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78441. if (this.showBackLines) {
  78442. // Back
  78443. engine.setDepthFunctionToGreaterOrEqual();
  78444. this._scene.resetCachedMaterial();
  78445. this._colorShader.setColor4("color", this.backColor.toColor4());
  78446. this._colorShader.bind(worldMatrix);
  78447. // Draw order
  78448. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78449. }
  78450. // Front
  78451. engine.setDepthFunctionToLess();
  78452. this._scene.resetCachedMaterial();
  78453. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78454. this._colorShader.bind(worldMatrix);
  78455. // Draw order
  78456. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78457. }
  78458. this._colorShader.unbind();
  78459. engine.setDepthFunctionToLessOrEqual();
  78460. engine.setDepthWrite(true);
  78461. };
  78462. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78463. this._prepareRessources();
  78464. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78465. return;
  78466. }
  78467. var engine = this._scene.getEngine();
  78468. engine.setDepthWrite(false);
  78469. engine.setColorWrite(false);
  78470. this._colorShader._preBind();
  78471. var boundingBox = mesh._boundingInfo.boundingBox;
  78472. var min = boundingBox.minimum;
  78473. var max = boundingBox.maximum;
  78474. var diff = max.subtract(min);
  78475. var median = min.add(diff.scale(0.5));
  78476. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78477. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78478. .multiply(boundingBox.getWorldMatrix());
  78479. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78480. engine.setDepthFunctionToLess();
  78481. this._scene.resetCachedMaterial();
  78482. this._colorShader.bind(worldMatrix);
  78483. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78484. this._colorShader.unbind();
  78485. engine.setDepthFunctionToLessOrEqual();
  78486. engine.setDepthWrite(true);
  78487. engine.setColorWrite(true);
  78488. };
  78489. BoundingBoxRenderer.prototype.dispose = function () {
  78490. if (!this._colorShader) {
  78491. return;
  78492. }
  78493. this.renderList.dispose();
  78494. this._colorShader.dispose();
  78495. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78496. if (buffer) {
  78497. buffer.dispose();
  78498. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78499. }
  78500. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78501. };
  78502. return BoundingBoxRenderer;
  78503. }());
  78504. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78505. })(BABYLON || (BABYLON = {}));
  78506. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78507. var BABYLON;
  78508. (function (BABYLON) {
  78509. var MorphTarget = /** @class */ (function () {
  78510. function MorphTarget(name, influence) {
  78511. if (influence === void 0) { influence = 0; }
  78512. this.name = name;
  78513. this.animations = new Array();
  78514. this._positions = null;
  78515. this._normals = null;
  78516. this._tangents = null;
  78517. this.onInfluenceChanged = new BABYLON.Observable();
  78518. this.influence = influence;
  78519. }
  78520. Object.defineProperty(MorphTarget.prototype, "influence", {
  78521. get: function () {
  78522. return this._influence;
  78523. },
  78524. set: function (influence) {
  78525. if (this._influence === influence) {
  78526. return;
  78527. }
  78528. var previous = this._influence;
  78529. this._influence = influence;
  78530. if (this.onInfluenceChanged.hasObservers) {
  78531. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78532. }
  78533. },
  78534. enumerable: true,
  78535. configurable: true
  78536. });
  78537. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78538. get: function () {
  78539. return !!this._positions;
  78540. },
  78541. enumerable: true,
  78542. configurable: true
  78543. });
  78544. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78545. get: function () {
  78546. return !!this._normals;
  78547. },
  78548. enumerable: true,
  78549. configurable: true
  78550. });
  78551. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78552. get: function () {
  78553. return !!this._tangents;
  78554. },
  78555. enumerable: true,
  78556. configurable: true
  78557. });
  78558. MorphTarget.prototype.setPositions = function (data) {
  78559. this._positions = data;
  78560. };
  78561. MorphTarget.prototype.getPositions = function () {
  78562. return this._positions;
  78563. };
  78564. MorphTarget.prototype.setNormals = function (data) {
  78565. this._normals = data;
  78566. };
  78567. MorphTarget.prototype.getNormals = function () {
  78568. return this._normals;
  78569. };
  78570. MorphTarget.prototype.setTangents = function (data) {
  78571. this._tangents = data;
  78572. };
  78573. MorphTarget.prototype.getTangents = function () {
  78574. return this._tangents;
  78575. };
  78576. /**
  78577. * Serializes the current target into a Serialization object.
  78578. * Returns the serialized object.
  78579. */
  78580. MorphTarget.prototype.serialize = function () {
  78581. var serializationObject = {};
  78582. serializationObject.name = this.name;
  78583. serializationObject.influence = this.influence;
  78584. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78585. if (this.hasNormals) {
  78586. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78587. }
  78588. if (this.hasTangents) {
  78589. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78590. }
  78591. // Animations
  78592. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78593. return serializationObject;
  78594. };
  78595. // Statics
  78596. MorphTarget.Parse = function (serializationObject) {
  78597. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78598. result.setPositions(serializationObject.positions);
  78599. if (serializationObject.normals) {
  78600. result.setNormals(serializationObject.normals);
  78601. }
  78602. if (serializationObject.tangents) {
  78603. result.setTangents(serializationObject.tangents);
  78604. }
  78605. // Animations
  78606. if (serializationObject.animations) {
  78607. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78608. var parsedAnimation = serializationObject.animations[animationIndex];
  78609. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78610. }
  78611. }
  78612. return result;
  78613. };
  78614. MorphTarget.FromMesh = function (mesh, name, influence) {
  78615. if (!name) {
  78616. name = mesh.name;
  78617. }
  78618. var result = new MorphTarget(name, influence);
  78619. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78621. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78622. }
  78623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78624. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78625. }
  78626. return result;
  78627. };
  78628. return MorphTarget;
  78629. }());
  78630. BABYLON.MorphTarget = MorphTarget;
  78631. })(BABYLON || (BABYLON = {}));
  78632. //# sourceMappingURL=babylon.morphTarget.js.map
  78633. var BABYLON;
  78634. (function (BABYLON) {
  78635. var MorphTargetManager = /** @class */ (function () {
  78636. function MorphTargetManager(scene) {
  78637. if (scene === void 0) { scene = null; }
  78638. this._targets = new Array();
  78639. this._targetObservable = new Array();
  78640. this._activeTargets = new BABYLON.SmartArray(16);
  78641. this._supportsNormals = false;
  78642. this._supportsTangents = false;
  78643. this._vertexCount = 0;
  78644. this._uniqueId = 0;
  78645. this._tempInfluences = new Array();
  78646. if (!scene) {
  78647. scene = BABYLON.Engine.LastCreatedScene;
  78648. }
  78649. this._scene = scene;
  78650. if (this._scene) {
  78651. this._scene.morphTargetManagers.push(this);
  78652. this._uniqueId = this._scene.getUniqueId();
  78653. }
  78654. }
  78655. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78656. get: function () {
  78657. return this._uniqueId;
  78658. },
  78659. enumerable: true,
  78660. configurable: true
  78661. });
  78662. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78663. get: function () {
  78664. return this._vertexCount;
  78665. },
  78666. enumerable: true,
  78667. configurable: true
  78668. });
  78669. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78670. get: function () {
  78671. return this._supportsNormals;
  78672. },
  78673. enumerable: true,
  78674. configurable: true
  78675. });
  78676. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78677. get: function () {
  78678. return this._supportsTangents;
  78679. },
  78680. enumerable: true,
  78681. configurable: true
  78682. });
  78683. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78684. get: function () {
  78685. return this._targets.length;
  78686. },
  78687. enumerable: true,
  78688. configurable: true
  78689. });
  78690. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78691. get: function () {
  78692. return this._activeTargets.length;
  78693. },
  78694. enumerable: true,
  78695. configurable: true
  78696. });
  78697. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78698. get: function () {
  78699. return this._influences;
  78700. },
  78701. enumerable: true,
  78702. configurable: true
  78703. });
  78704. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78705. return this._activeTargets.data[index];
  78706. };
  78707. MorphTargetManager.prototype.getTarget = function (index) {
  78708. return this._targets[index];
  78709. };
  78710. MorphTargetManager.prototype.addTarget = function (target) {
  78711. var _this = this;
  78712. this._targets.push(target);
  78713. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78714. _this._syncActiveTargets(needUpdate);
  78715. }));
  78716. this._syncActiveTargets(true);
  78717. };
  78718. MorphTargetManager.prototype.removeTarget = function (target) {
  78719. var index = this._targets.indexOf(target);
  78720. if (index >= 0) {
  78721. this._targets.splice(index, 1);
  78722. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78723. this._syncActiveTargets(true);
  78724. }
  78725. };
  78726. /**
  78727. * Serializes the current manager into a Serialization object.
  78728. * Returns the serialized object.
  78729. */
  78730. MorphTargetManager.prototype.serialize = function () {
  78731. var serializationObject = {};
  78732. serializationObject.id = this.uniqueId;
  78733. serializationObject.targets = [];
  78734. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78735. var target = _a[_i];
  78736. serializationObject.targets.push(target.serialize());
  78737. }
  78738. return serializationObject;
  78739. };
  78740. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78741. var influenceCount = 0;
  78742. this._activeTargets.reset();
  78743. this._supportsNormals = true;
  78744. this._supportsTangents = true;
  78745. this._vertexCount = 0;
  78746. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78747. var target = _a[_i];
  78748. this._activeTargets.push(target);
  78749. this._tempInfluences[influenceCount++] = target.influence;
  78750. var positions = target.getPositions();
  78751. if (positions) {
  78752. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78753. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78754. var vertexCount = positions.length / 3;
  78755. if (this._vertexCount === 0) {
  78756. this._vertexCount = vertexCount;
  78757. }
  78758. else if (this._vertexCount !== vertexCount) {
  78759. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78760. return;
  78761. }
  78762. }
  78763. }
  78764. if (!this._influences || this._influences.length !== influenceCount) {
  78765. this._influences = new Float32Array(influenceCount);
  78766. }
  78767. for (var index = 0; index < influenceCount; index++) {
  78768. this._influences[index] = this._tempInfluences[index];
  78769. }
  78770. if (needUpdate && this._scene) {
  78771. // Flag meshes as dirty to resync with the active targets
  78772. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78773. var mesh = _c[_b];
  78774. if (mesh.morphTargetManager === this) {
  78775. mesh._syncGeometryWithMorphTargetManager();
  78776. }
  78777. }
  78778. }
  78779. };
  78780. // Statics
  78781. MorphTargetManager.Parse = function (serializationObject, scene) {
  78782. var result = new MorphTargetManager(scene);
  78783. result._uniqueId = serializationObject.id;
  78784. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78785. var targetData = _a[_i];
  78786. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78787. }
  78788. return result;
  78789. };
  78790. return MorphTargetManager;
  78791. }());
  78792. BABYLON.MorphTargetManager = MorphTargetManager;
  78793. })(BABYLON || (BABYLON = {}));
  78794. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78795. var BABYLON;
  78796. (function (BABYLON) {
  78797. var Octree = /** @class */ (function () {
  78798. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78799. if (maxDepth === void 0) { maxDepth = 2; }
  78800. this.maxDepth = maxDepth;
  78801. this.dynamicContent = new Array();
  78802. this._maxBlockCapacity = maxBlockCapacity || 64;
  78803. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78804. this._creationFunc = creationFunc;
  78805. }
  78806. // Methods
  78807. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78808. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78809. };
  78810. Octree.prototype.addMesh = function (entry) {
  78811. for (var index = 0; index < this.blocks.length; index++) {
  78812. var block = this.blocks[index];
  78813. block.addEntry(entry);
  78814. }
  78815. };
  78816. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78817. this._selectionContent.reset();
  78818. for (var index = 0; index < this.blocks.length; index++) {
  78819. var block = this.blocks[index];
  78820. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78821. }
  78822. if (allowDuplicate) {
  78823. this._selectionContent.concat(this.dynamicContent);
  78824. }
  78825. else {
  78826. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78827. }
  78828. return this._selectionContent;
  78829. };
  78830. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78831. this._selectionContent.reset();
  78832. for (var index = 0; index < this.blocks.length; index++) {
  78833. var block = this.blocks[index];
  78834. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78835. }
  78836. if (allowDuplicate) {
  78837. this._selectionContent.concat(this.dynamicContent);
  78838. }
  78839. else {
  78840. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78841. }
  78842. return this._selectionContent;
  78843. };
  78844. Octree.prototype.intersectsRay = function (ray) {
  78845. this._selectionContent.reset();
  78846. for (var index = 0; index < this.blocks.length; index++) {
  78847. var block = this.blocks[index];
  78848. block.intersectsRay(ray, this._selectionContent);
  78849. }
  78850. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78851. return this._selectionContent;
  78852. };
  78853. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78854. target.blocks = new Array();
  78855. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78856. // Segmenting space
  78857. for (var x = 0; x < 2; x++) {
  78858. for (var y = 0; y < 2; y++) {
  78859. for (var z = 0; z < 2; z++) {
  78860. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78861. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78862. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78863. block.addEntries(entries);
  78864. target.blocks.push(block);
  78865. }
  78866. }
  78867. }
  78868. };
  78869. Octree.CreationFuncForMeshes = function (entry, block) {
  78870. var boundingInfo = entry.getBoundingInfo();
  78871. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78872. block.entries.push(entry);
  78873. }
  78874. };
  78875. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78876. var boundingInfo = entry.getBoundingInfo();
  78877. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78878. block.entries.push(entry);
  78879. }
  78880. };
  78881. return Octree;
  78882. }());
  78883. BABYLON.Octree = Octree;
  78884. })(BABYLON || (BABYLON = {}));
  78885. //# sourceMappingURL=babylon.octree.js.map
  78886. var BABYLON;
  78887. (function (BABYLON) {
  78888. var OctreeBlock = /** @class */ (function () {
  78889. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78890. this.entries = new Array();
  78891. this._boundingVectors = new Array();
  78892. this._capacity = capacity;
  78893. this._depth = depth;
  78894. this._maxDepth = maxDepth;
  78895. this._creationFunc = creationFunc;
  78896. this._minPoint = minPoint;
  78897. this._maxPoint = maxPoint;
  78898. this._boundingVectors.push(minPoint.clone());
  78899. this._boundingVectors.push(maxPoint.clone());
  78900. this._boundingVectors.push(minPoint.clone());
  78901. this._boundingVectors[2].x = maxPoint.x;
  78902. this._boundingVectors.push(minPoint.clone());
  78903. this._boundingVectors[3].y = maxPoint.y;
  78904. this._boundingVectors.push(minPoint.clone());
  78905. this._boundingVectors[4].z = maxPoint.z;
  78906. this._boundingVectors.push(maxPoint.clone());
  78907. this._boundingVectors[5].z = minPoint.z;
  78908. this._boundingVectors.push(maxPoint.clone());
  78909. this._boundingVectors[6].x = minPoint.x;
  78910. this._boundingVectors.push(maxPoint.clone());
  78911. this._boundingVectors[7].y = minPoint.y;
  78912. }
  78913. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78914. // Property
  78915. get: function () {
  78916. return this._capacity;
  78917. },
  78918. enumerable: true,
  78919. configurable: true
  78920. });
  78921. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78922. get: function () {
  78923. return this._minPoint;
  78924. },
  78925. enumerable: true,
  78926. configurable: true
  78927. });
  78928. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78929. get: function () {
  78930. return this._maxPoint;
  78931. },
  78932. enumerable: true,
  78933. configurable: true
  78934. });
  78935. // Methods
  78936. OctreeBlock.prototype.addEntry = function (entry) {
  78937. if (this.blocks) {
  78938. for (var index = 0; index < this.blocks.length; index++) {
  78939. var block = this.blocks[index];
  78940. block.addEntry(entry);
  78941. }
  78942. return;
  78943. }
  78944. this._creationFunc(entry, this);
  78945. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78946. this.createInnerBlocks();
  78947. }
  78948. };
  78949. OctreeBlock.prototype.addEntries = function (entries) {
  78950. for (var index = 0; index < entries.length; index++) {
  78951. var mesh = entries[index];
  78952. this.addEntry(mesh);
  78953. }
  78954. };
  78955. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78956. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78957. if (this.blocks) {
  78958. for (var index = 0; index < this.blocks.length; index++) {
  78959. var block = this.blocks[index];
  78960. block.select(frustumPlanes, selection, allowDuplicate);
  78961. }
  78962. return;
  78963. }
  78964. if (allowDuplicate) {
  78965. selection.concat(this.entries);
  78966. }
  78967. else {
  78968. selection.concatWithNoDuplicate(this.entries);
  78969. }
  78970. }
  78971. };
  78972. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78973. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78974. if (this.blocks) {
  78975. for (var index = 0; index < this.blocks.length; index++) {
  78976. var block = this.blocks[index];
  78977. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78978. }
  78979. return;
  78980. }
  78981. if (allowDuplicate) {
  78982. selection.concat(this.entries);
  78983. }
  78984. else {
  78985. selection.concatWithNoDuplicate(this.entries);
  78986. }
  78987. }
  78988. };
  78989. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78990. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78991. if (this.blocks) {
  78992. for (var index = 0; index < this.blocks.length; index++) {
  78993. var block = this.blocks[index];
  78994. block.intersectsRay(ray, selection);
  78995. }
  78996. return;
  78997. }
  78998. selection.concatWithNoDuplicate(this.entries);
  78999. }
  79000. };
  79001. OctreeBlock.prototype.createInnerBlocks = function () {
  79002. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79003. };
  79004. return OctreeBlock;
  79005. }());
  79006. BABYLON.OctreeBlock = OctreeBlock;
  79007. })(BABYLON || (BABYLON = {}));
  79008. //# sourceMappingURL=babylon.octreeBlock.js.map
  79009. var BABYLON;
  79010. (function (BABYLON) {
  79011. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79012. __extends(VRDistortionCorrectionPostProcess, _super);
  79013. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79014. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79015. 'LensCenter',
  79016. 'Scale',
  79017. 'ScaleIn',
  79018. 'HmdWarpParam'
  79019. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79020. _this._isRightEye = isRightEye;
  79021. _this._distortionFactors = vrMetrics.distortionK;
  79022. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79023. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79024. _this.adaptScaleToCurrentViewport = true;
  79025. _this.onSizeChangedObservable.add(function () {
  79026. _this.aspectRatio = _this.width * .5 / _this.height;
  79027. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79028. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79029. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79030. });
  79031. _this.onApplyObservable.add(function (effect) {
  79032. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79033. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79034. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79035. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79036. });
  79037. return _this;
  79038. }
  79039. return VRDistortionCorrectionPostProcess;
  79040. }(BABYLON.PostProcess));
  79041. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79042. })(BABYLON || (BABYLON = {}));
  79043. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79044. var BABYLON;
  79045. (function (BABYLON) {
  79046. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79047. __extends(AnaglyphPostProcess, _super);
  79048. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79049. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79050. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79051. _this.onApplyObservable.add(function (effect) {
  79052. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79053. });
  79054. return _this;
  79055. }
  79056. return AnaglyphPostProcess;
  79057. }(BABYLON.PostProcess));
  79058. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79059. })(BABYLON || (BABYLON = {}));
  79060. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79061. var BABYLON;
  79062. (function (BABYLON) {
  79063. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79064. __extends(StereoscopicInterlacePostProcess, _super);
  79065. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79066. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79067. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79068. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79069. _this.onSizeChangedObservable.add(function () {
  79070. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79071. });
  79072. _this.onApplyObservable.add(function (effect) {
  79073. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79074. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79075. });
  79076. return _this;
  79077. }
  79078. return StereoscopicInterlacePostProcess;
  79079. }(BABYLON.PostProcess));
  79080. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79081. })(BABYLON || (BABYLON = {}));
  79082. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79083. var BABYLON;
  79084. (function (BABYLON) {
  79085. /**
  79086. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79087. * Screen rotation is taken into account.
  79088. */
  79089. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79090. function FreeCameraDeviceOrientationInput() {
  79091. var _this = this;
  79092. this._screenOrientationAngle = 0;
  79093. this._screenQuaternion = new BABYLON.Quaternion();
  79094. this._alpha = 0;
  79095. this._beta = 0;
  79096. this._gamma = 0;
  79097. this._orientationChanged = function () {
  79098. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79099. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79100. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79101. };
  79102. this._deviceOrientation = function (evt) {
  79103. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79104. _this._beta = evt.beta !== null ? evt.beta : 0;
  79105. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79106. };
  79107. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79108. this._orientationChanged();
  79109. }
  79110. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79111. get: function () {
  79112. return this._camera;
  79113. },
  79114. set: function (camera) {
  79115. this._camera = camera;
  79116. if (this._camera != null && !this._camera.rotationQuaternion) {
  79117. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79118. }
  79119. },
  79120. enumerable: true,
  79121. configurable: true
  79122. });
  79123. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79124. window.addEventListener("orientationchange", this._orientationChanged);
  79125. window.addEventListener("deviceorientation", this._deviceOrientation);
  79126. //In certain cases, the attach control is called AFTER orientation was changed,
  79127. //So this is needed.
  79128. this._orientationChanged();
  79129. };
  79130. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79131. window.removeEventListener("orientationchange", this._orientationChanged);
  79132. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79133. };
  79134. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79135. //if no device orientation provided, don't update the rotation.
  79136. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79137. if (!this._alpha)
  79138. return;
  79139. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79140. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79141. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79142. //Mirror on XY Plane
  79143. this._camera.rotationQuaternion.z *= -1;
  79144. this._camera.rotationQuaternion.w *= -1;
  79145. };
  79146. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79147. return "FreeCameraDeviceOrientationInput";
  79148. };
  79149. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79150. return "deviceOrientation";
  79151. };
  79152. return FreeCameraDeviceOrientationInput;
  79153. }());
  79154. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79155. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79156. })(BABYLON || (BABYLON = {}));
  79157. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79158. var BABYLON;
  79159. (function (BABYLON) {
  79160. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79161. function ArcRotateCameraVRDeviceOrientationInput() {
  79162. this.alphaCorrection = 1;
  79163. this.betaCorrection = 1;
  79164. this.gammaCorrection = 1;
  79165. this._alpha = 0;
  79166. this._gamma = 0;
  79167. this._dirty = false;
  79168. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79169. }
  79170. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79171. this.camera.attachControl(element, noPreventDefault);
  79172. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79173. };
  79174. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79175. if (evt.alpha !== null) {
  79176. this._alpha = +evt.alpha | 0;
  79177. }
  79178. if (evt.gamma !== null) {
  79179. this._gamma = +evt.gamma | 0;
  79180. }
  79181. this._dirty = true;
  79182. };
  79183. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79184. if (this._dirty) {
  79185. this._dirty = false;
  79186. if (this._gamma < 0) {
  79187. this._gamma = 180 + this._gamma;
  79188. }
  79189. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79190. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79191. }
  79192. };
  79193. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79194. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79195. };
  79196. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79197. return "ArcRotateCameraVRDeviceOrientationInput";
  79198. };
  79199. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79200. return "VRDeviceOrientation";
  79201. };
  79202. return ArcRotateCameraVRDeviceOrientationInput;
  79203. }());
  79204. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79205. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79206. })(BABYLON || (BABYLON = {}));
  79207. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79208. var BABYLON;
  79209. (function (BABYLON) {
  79210. var VRCameraMetrics = /** @class */ (function () {
  79211. function VRCameraMetrics() {
  79212. this.compensateDistortion = true;
  79213. }
  79214. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79215. get: function () {
  79216. return this.hResolution / (2 * this.vResolution);
  79217. },
  79218. enumerable: true,
  79219. configurable: true
  79220. });
  79221. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79222. get: function () {
  79223. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79224. },
  79225. enumerable: true,
  79226. configurable: true
  79227. });
  79228. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79229. get: function () {
  79230. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79231. var h = (4 * meters) / this.hScreenSize;
  79232. return BABYLON.Matrix.Translation(h, 0, 0);
  79233. },
  79234. enumerable: true,
  79235. configurable: true
  79236. });
  79237. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79238. get: function () {
  79239. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79240. var h = (4 * meters) / this.hScreenSize;
  79241. return BABYLON.Matrix.Translation(-h, 0, 0);
  79242. },
  79243. enumerable: true,
  79244. configurable: true
  79245. });
  79246. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79247. get: function () {
  79248. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79254. get: function () {
  79255. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79256. },
  79257. enumerable: true,
  79258. configurable: true
  79259. });
  79260. VRCameraMetrics.GetDefault = function () {
  79261. var result = new VRCameraMetrics();
  79262. result.hResolution = 1280;
  79263. result.vResolution = 800;
  79264. result.hScreenSize = 0.149759993;
  79265. result.vScreenSize = 0.0935999975;
  79266. result.vScreenCenter = 0.0467999987;
  79267. result.eyeToScreenDistance = 0.0410000011;
  79268. result.lensSeparationDistance = 0.0635000020;
  79269. result.interpupillaryDistance = 0.0640000030;
  79270. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79271. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79272. result.postProcessScaleFactor = 1.714605507808412;
  79273. result.lensCenterOffset = 0.151976421;
  79274. return result;
  79275. };
  79276. return VRCameraMetrics;
  79277. }());
  79278. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79279. })(BABYLON || (BABYLON = {}));
  79280. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79281. var BABYLON;
  79282. (function (BABYLON) {
  79283. /**
  79284. * This represents a WebVR camera.
  79285. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79286. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79287. */
  79288. var WebVRFreeCamera = /** @class */ (function (_super) {
  79289. __extends(WebVRFreeCamera, _super);
  79290. /**
  79291. * Instantiates a WebVRFreeCamera.
  79292. * @param name The name of the WebVRFreeCamera
  79293. * @param position The starting anchor position for the camera
  79294. * @param scene The scene the camera belongs to
  79295. * @param webVROptions a set of customizable options for the webVRCamera
  79296. */
  79297. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79298. if (webVROptions === void 0) { webVROptions = {}; }
  79299. var _this = _super.call(this, name, position, scene) || this;
  79300. _this.webVROptions = webVROptions;
  79301. /**
  79302. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79303. */
  79304. _this._vrDevice = null;
  79305. /**
  79306. * The rawPose of the vrDevice.
  79307. */
  79308. _this.rawPose = null;
  79309. _this._specsVersion = "1.1";
  79310. _this._attached = false;
  79311. _this._descendants = [];
  79312. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79313. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79314. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79315. _this._standingMatrix = null;
  79316. /**
  79317. * Represents device position in babylon space.
  79318. */
  79319. _this.devicePosition = BABYLON.Vector3.Zero();
  79320. /**
  79321. * Represents device rotation in babylon space.
  79322. */
  79323. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79324. /**
  79325. * The scale of the device to be used when translating from device space to babylon space.
  79326. */
  79327. _this.deviceScaleFactor = 1;
  79328. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79329. _this._worldToDevice = BABYLON.Matrix.Identity();
  79330. /**
  79331. * References to the webVR controllers for the vrDevice.
  79332. */
  79333. _this.controllers = [];
  79334. /**
  79335. * Emits an event when a controller is attached.
  79336. */
  79337. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79338. /**
  79339. * Emits an event when a controller's mesh has been loaded;
  79340. */
  79341. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79342. /**
  79343. * If the rig cameras be used as parent instead of this camera.
  79344. */
  79345. _this.rigParenting = true;
  79346. _this._defaultHeight = undefined;
  79347. _this._workingVector = BABYLON.Vector3.Zero();
  79348. _this._oneVector = BABYLON.Vector3.One();
  79349. _this._workingMatrix = BABYLON.Matrix.Identity();
  79350. _this._cache.position = BABYLON.Vector3.Zero();
  79351. if (webVROptions.defaultHeight) {
  79352. _this._defaultHeight = webVROptions.defaultHeight;
  79353. _this.position.y = _this._defaultHeight;
  79354. }
  79355. _this.minZ = 0.1;
  79356. //legacy support - the compensation boolean was removed.
  79357. if (arguments.length === 5) {
  79358. _this.webVROptions = arguments[4];
  79359. }
  79360. // default webVR options
  79361. if (_this.webVROptions.trackPosition == undefined) {
  79362. _this.webVROptions.trackPosition = true;
  79363. }
  79364. if (_this.webVROptions.controllerMeshes == undefined) {
  79365. _this.webVROptions.controllerMeshes = true;
  79366. }
  79367. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79368. _this.webVROptions.defaultLightingOnControllers = true;
  79369. }
  79370. _this.rotationQuaternion = new BABYLON.Quaternion();
  79371. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79372. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79373. }
  79374. //enable VR
  79375. var engine = _this.getEngine();
  79376. _this._onVREnabled = function (success) { if (success) {
  79377. _this.initControllers();
  79378. } };
  79379. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79380. engine.initWebVR().add(function (event) {
  79381. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79382. return;
  79383. }
  79384. _this._vrDevice = event.vrDisplay;
  79385. //reset the rig parameters.
  79386. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79387. if (_this._attached) {
  79388. _this.getEngine().enableVR();
  79389. }
  79390. });
  79391. if (typeof (VRFrameData) !== "undefined")
  79392. _this._frameData = new VRFrameData();
  79393. /**
  79394. * The idea behind the following lines:
  79395. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79396. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79397. * the second will not show it correctly.
  79398. *
  79399. * To solve this - each object that has the camera as parent will be added to a protected array.
  79400. * When the rig camera renders, it will take this array and set all of those to be its children.
  79401. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79402. * Amazing!
  79403. */
  79404. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79405. if (camera.parent === _this && _this.rigParenting) {
  79406. _this._descendants = _this.getDescendants(true, function (n) {
  79407. // don't take the cameras or the controllers!
  79408. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79409. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79410. return !isController && !isRigCamera;
  79411. });
  79412. _this._descendants.forEach(function (node) {
  79413. node.parent = camera;
  79414. });
  79415. }
  79416. });
  79417. scene.onAfterCameraRenderObservable.add(function (camera) {
  79418. if (camera.parent === _this && _this.rigParenting) {
  79419. _this._descendants.forEach(function (node) {
  79420. node.parent = _this;
  79421. });
  79422. }
  79423. });
  79424. return _this;
  79425. }
  79426. /**
  79427. * Gets the device distance from the ground in meters.
  79428. * @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.
  79429. */
  79430. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79431. if (this._standingMatrix) {
  79432. // Add standing matrix offset to get real offset from ground in room
  79433. this._standingMatrix.getTranslationToRef(this._workingVector);
  79434. return this._deviceRoomPosition.y + this._workingVector.y;
  79435. }
  79436. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79437. return this._defaultHeight || 0;
  79438. };
  79439. /**
  79440. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79441. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79442. */
  79443. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79444. var _this = this;
  79445. if (callback === void 0) { callback = function (bool) { }; }
  79446. // Use standing matrix if available
  79447. this.getEngine().initWebVRAsync().then(function (result) {
  79448. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79449. callback(false);
  79450. }
  79451. else {
  79452. _this._standingMatrix = new BABYLON.Matrix();
  79453. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79454. if (!_this.getScene().useRightHandedSystem) {
  79455. [2, 6, 8, 9, 14].forEach(function (num) {
  79456. if (_this._standingMatrix) {
  79457. _this._standingMatrix.m[num] *= -1;
  79458. }
  79459. });
  79460. }
  79461. callback(true);
  79462. }
  79463. });
  79464. };
  79465. /**
  79466. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79467. * @returns A promise with a boolean set to if the standing matrix is supported.
  79468. */
  79469. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79470. var _this = this;
  79471. return new Promise(function (res, rej) {
  79472. _this.useStandingMatrix(function (supported) {
  79473. res(supported);
  79474. });
  79475. });
  79476. };
  79477. /**
  79478. * Disposes the camera
  79479. */
  79480. WebVRFreeCamera.prototype.dispose = function () {
  79481. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79482. _super.prototype.dispose.call(this);
  79483. };
  79484. /**
  79485. * Gets a vrController by name.
  79486. * @param name The name of the controller to retreive
  79487. * @returns the controller matching the name specified or null if not found
  79488. */
  79489. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79490. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79491. var gp = _a[_i];
  79492. if (gp.hand === name) {
  79493. return gp;
  79494. }
  79495. }
  79496. return null;
  79497. };
  79498. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79499. /**
  79500. * The controller corrisponding to the users left hand.
  79501. */
  79502. get: function () {
  79503. if (!this._leftController) {
  79504. this._leftController = this.getControllerByName("left");
  79505. }
  79506. return this._leftController;
  79507. },
  79508. enumerable: true,
  79509. configurable: true
  79510. });
  79511. ;
  79512. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79513. /**
  79514. * The controller corrisponding to the users right hand.
  79515. */
  79516. get: function () {
  79517. if (!this._rightController) {
  79518. this._rightController = this.getControllerByName("right");
  79519. }
  79520. return this._rightController;
  79521. },
  79522. enumerable: true,
  79523. configurable: true
  79524. });
  79525. ;
  79526. /**
  79527. * Casts a ray forward from the vrCamera's gaze.
  79528. * @param length Length of the ray (default: 100)
  79529. * @returns the ray corrisponding to the gaze
  79530. */
  79531. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79532. if (length === void 0) { length = 100; }
  79533. if (this.leftCamera) {
  79534. // Use left eye to avoid computation to compute center on every call
  79535. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79536. }
  79537. else {
  79538. return _super.prototype.getForwardRay.call(this, length);
  79539. }
  79540. };
  79541. /**
  79542. * Updates the camera based on device's frame data
  79543. */
  79544. WebVRFreeCamera.prototype._checkInputs = function () {
  79545. if (this._vrDevice && this._vrDevice.isPresenting) {
  79546. this._vrDevice.getFrameData(this._frameData);
  79547. this.updateFromDevice(this._frameData.pose);
  79548. }
  79549. _super.prototype._checkInputs.call(this);
  79550. };
  79551. /**
  79552. * Updates the poseControlled values based on the input device pose.
  79553. * @param poseData Pose coming from the device
  79554. */
  79555. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79556. if (poseData && poseData.orientation) {
  79557. this.rawPose = poseData;
  79558. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79559. if (this.getScene().useRightHandedSystem) {
  79560. this._deviceRoomRotationQuaternion.z *= -1;
  79561. this._deviceRoomRotationQuaternion.w *= -1;
  79562. }
  79563. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79564. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79565. if (this.getScene().useRightHandedSystem) {
  79566. this._deviceRoomPosition.z *= -1;
  79567. }
  79568. }
  79569. }
  79570. };
  79571. /**
  79572. * WebVR's attach control will start broadcasting frames to the device.
  79573. * Note that in certain browsers (chrome for example) this function must be called
  79574. * within a user-interaction callback. Example:
  79575. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79576. *
  79577. * @param element html element to attach the vrDevice to
  79578. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79579. */
  79580. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79581. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79582. this._attached = true;
  79583. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79584. if (this._vrDevice) {
  79585. this.getEngine().enableVR();
  79586. }
  79587. };
  79588. /**
  79589. * Detaches the camera from the html element and disables VR
  79590. *
  79591. * @param element html element to detach from
  79592. */
  79593. WebVRFreeCamera.prototype.detachControl = function (element) {
  79594. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79595. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79596. _super.prototype.detachControl.call(this, element);
  79597. this._attached = false;
  79598. this.getEngine().disableVR();
  79599. };
  79600. /**
  79601. * @returns the name of this class
  79602. */
  79603. WebVRFreeCamera.prototype.getClassName = function () {
  79604. return "WebVRFreeCamera";
  79605. };
  79606. /**
  79607. * Calls resetPose on the vrDisplay
  79608. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79609. */
  79610. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79611. //uses the vrDisplay's "resetPose()".
  79612. //pitch and roll won't be affected.
  79613. this._vrDevice.resetPose();
  79614. };
  79615. /**
  79616. * Updates the rig cameras (left and right eye)
  79617. */
  79618. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79619. var camLeft = this._rigCameras[0];
  79620. var camRight = this._rigCameras[1];
  79621. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79622. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79623. camLeft.position.copyFrom(this._deviceRoomPosition);
  79624. camRight.position.copyFrom(this._deviceRoomPosition);
  79625. };
  79626. /**
  79627. * Updates the cached values of the camera
  79628. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79629. */
  79630. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79631. var _this = this;
  79632. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79633. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79634. if (!this.updateCacheCalled) {
  79635. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79636. this.updateCacheCalled = true;
  79637. this.update();
  79638. }
  79639. // Set working vector to the device position in room space rotated by the new rotation
  79640. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79641. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79642. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79643. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79644. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79645. // Add translation from anchor position
  79646. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79647. this._workingVector.addInPlace(this.position);
  79648. this._workingVector.subtractInPlace(this._cache.position);
  79649. this._deviceToWorld.setTranslation(this._workingVector);
  79650. // Set an inverted matrix to be used when updating the camera
  79651. this._deviceToWorld.invertToRef(this._worldToDevice);
  79652. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79653. this.controllers.forEach(function (controller) {
  79654. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79655. controller.update();
  79656. });
  79657. }
  79658. if (!ignoreParentClass) {
  79659. _super.prototype._updateCache.call(this);
  79660. }
  79661. this.updateCacheCalled = false;
  79662. };
  79663. /**
  79664. * Updates the current device position and rotation in the babylon world
  79665. */
  79666. WebVRFreeCamera.prototype.update = function () {
  79667. // Get current device position in babylon world
  79668. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79669. // Get current device rotation in babylon world
  79670. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79671. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79672. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79673. _super.prototype.update.call(this);
  79674. };
  79675. /**
  79676. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79677. * @returns an identity matrix
  79678. */
  79679. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79680. return BABYLON.Matrix.Identity();
  79681. };
  79682. /**
  79683. * This function is called by the two RIG cameras.
  79684. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79685. */
  79686. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79687. var _this = this;
  79688. // Update the parent camera prior to using a child camera to avoid desynchronization
  79689. var parentCamera = this._cameraRigParams["parentCamera"];
  79690. parentCamera._updateCache();
  79691. //WebVR 1.1
  79692. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79693. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79694. if (!this.getScene().useRightHandedSystem) {
  79695. [2, 6, 8, 9, 14].forEach(function (num) {
  79696. _this._webvrViewMatrix.m[num] *= -1;
  79697. });
  79698. }
  79699. // update the camera rotation matrix
  79700. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79701. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79702. // Computing target and final matrix
  79703. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79704. // should the view matrix be updated with scale and position offset?
  79705. if (parentCamera.deviceScaleFactor !== 1) {
  79706. this._webvrViewMatrix.invert();
  79707. // scale the position, if set
  79708. if (parentCamera.deviceScaleFactor) {
  79709. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79710. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79711. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79712. }
  79713. this._webvrViewMatrix.invert();
  79714. }
  79715. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79716. return this._webvrViewMatrix;
  79717. };
  79718. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79719. var _this = this;
  79720. var parentCamera = this.parent;
  79721. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79722. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79723. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79724. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79725. //babylon compatible matrix
  79726. if (!this.getScene().useRightHandedSystem) {
  79727. [8, 9, 10, 11].forEach(function (num) {
  79728. _this._projectionMatrix.m[num] *= -1;
  79729. });
  79730. }
  79731. return this._projectionMatrix;
  79732. };
  79733. /**
  79734. * Initializes the controllers and their meshes
  79735. */
  79736. WebVRFreeCamera.prototype.initControllers = function () {
  79737. var _this = this;
  79738. this.controllers = [];
  79739. var manager = this.getScene().gamepadManager;
  79740. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79741. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79742. var webVrController = gamepad;
  79743. if (webVrController.defaultModel) {
  79744. webVrController.defaultModel.setEnabled(false);
  79745. }
  79746. if (webVrController.hand === "right") {
  79747. _this._rightController = null;
  79748. }
  79749. if (webVrController.hand === "left") {
  79750. _this._leftController = null;
  79751. }
  79752. var controllerIndex = _this.controllers.indexOf(webVrController);
  79753. if (controllerIndex !== -1) {
  79754. _this.controllers.splice(controllerIndex, 1);
  79755. }
  79756. }
  79757. });
  79758. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79759. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79760. var webVrController_1 = gamepad;
  79761. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  79762. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79763. if (_this.webVROptions.controllerMeshes) {
  79764. if (webVrController_1.defaultModel) {
  79765. webVrController_1.defaultModel.setEnabled(true);
  79766. }
  79767. else {
  79768. // Load the meshes
  79769. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79770. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  79771. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79772. if (_this.webVROptions.defaultLightingOnControllers) {
  79773. if (!_this._lightOnControllers) {
  79774. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79775. }
  79776. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79777. var children = mesh.getChildren();
  79778. if (children.length !== 0) {
  79779. children.forEach(function (mesh) {
  79780. light.includedOnlyMeshes.push(mesh);
  79781. activateLightOnSubMeshes_1(mesh, light);
  79782. });
  79783. }
  79784. };
  79785. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79786. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79787. }
  79788. });
  79789. }
  79790. }
  79791. webVrController_1.attachToPoseControlledCamera(_this);
  79792. // since this is async - sanity check. Is the controller already stored?
  79793. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79794. //add to the controllers array
  79795. _this.controllers.push(webVrController_1);
  79796. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79797. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79798. // So we're overriding setting left & right manually to be sure
  79799. var firstViveWandDetected = false;
  79800. for (var i = 0; i < _this.controllers.length; i++) {
  79801. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79802. if (!firstViveWandDetected) {
  79803. firstViveWandDetected = true;
  79804. _this.controllers[i].hand = "left";
  79805. }
  79806. else {
  79807. _this.controllers[i].hand = "right";
  79808. }
  79809. }
  79810. }
  79811. //did we find enough controllers? Great! let the developer know.
  79812. if (_this.controllers.length >= 2) {
  79813. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79814. }
  79815. }
  79816. }
  79817. });
  79818. };
  79819. return WebVRFreeCamera;
  79820. }(BABYLON.FreeCamera));
  79821. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79822. })(BABYLON || (BABYLON = {}));
  79823. //# sourceMappingURL=babylon.webVRCamera.js.map
  79824. var BABYLON;
  79825. (function (BABYLON) {
  79826. // We're mainly based on the logic defined into the FreeCamera code
  79827. /**
  79828. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79829. * being tilted forward or back and left or right.
  79830. */
  79831. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79832. __extends(DeviceOrientationCamera, _super);
  79833. /**
  79834. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79835. * @param name The name of the camera
  79836. * @param position The start position camera
  79837. * @param scene The scene the camera belongs to
  79838. */
  79839. function DeviceOrientationCamera(name, position, scene) {
  79840. var _this = _super.call(this, name, position, scene) || this;
  79841. _this._quaternionCache = new BABYLON.Quaternion();
  79842. _this.inputs.addDeviceOrientation();
  79843. return _this;
  79844. }
  79845. /**
  79846. * Gets the current instance class name ("DeviceOrientationCamera").
  79847. * This helps avoiding instanceof at run time.
  79848. * @returns the class name
  79849. */
  79850. DeviceOrientationCamera.prototype.getClassName = function () {
  79851. return "DeviceOrientationCamera";
  79852. };
  79853. /**
  79854. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79855. */
  79856. DeviceOrientationCamera.prototype._checkInputs = function () {
  79857. _super.prototype._checkInputs.call(this);
  79858. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79859. if (this._initialQuaternion) {
  79860. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79861. }
  79862. };
  79863. /**
  79864. * Reset the camera to its default orientation on the specified axis only.
  79865. * @param axis The axis to reset
  79866. */
  79867. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79868. var _this = this;
  79869. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79870. //can only work if this camera has a rotation quaternion already.
  79871. if (!this.rotationQuaternion)
  79872. return;
  79873. if (!this._initialQuaternion) {
  79874. this._initialQuaternion = new BABYLON.Quaternion();
  79875. }
  79876. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79877. ['x', 'y', 'z'].forEach(function (axisName) {
  79878. if (!axis[axisName]) {
  79879. _this._initialQuaternion[axisName] = 0;
  79880. }
  79881. else {
  79882. _this._initialQuaternion[axisName] *= -1;
  79883. }
  79884. });
  79885. this._initialQuaternion.normalize();
  79886. //force rotation update
  79887. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79888. };
  79889. return DeviceOrientationCamera;
  79890. }(BABYLON.FreeCamera));
  79891. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79892. })(BABYLON || (BABYLON = {}));
  79893. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79894. var BABYLON;
  79895. (function (BABYLON) {
  79896. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79897. __extends(VRDeviceOrientationFreeCamera, _super);
  79898. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79899. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79900. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79901. var _this = _super.call(this, name, position, scene) || this;
  79902. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79903. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79904. return _this;
  79905. }
  79906. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79907. return "VRDeviceOrientationFreeCamera";
  79908. };
  79909. return VRDeviceOrientationFreeCamera;
  79910. }(BABYLON.DeviceOrientationCamera));
  79911. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79912. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79913. __extends(VRDeviceOrientationGamepadCamera, _super);
  79914. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79915. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79916. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79917. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79918. _this.inputs.addGamepad();
  79919. return _this;
  79920. }
  79921. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79922. return "VRDeviceOrientationGamepadCamera";
  79923. };
  79924. return VRDeviceOrientationGamepadCamera;
  79925. }(VRDeviceOrientationFreeCamera));
  79926. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79927. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79928. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79929. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79930. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79931. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79932. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79933. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79934. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79935. _this.inputs.addVRDeviceOrientation();
  79936. return _this;
  79937. }
  79938. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79939. return "VRDeviceOrientationArcRotateCamera";
  79940. };
  79941. return VRDeviceOrientationArcRotateCamera;
  79942. }(BABYLON.ArcRotateCamera));
  79943. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79944. })(BABYLON || (BABYLON = {}));
  79945. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79946. var BABYLON;
  79947. (function (BABYLON) {
  79948. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79949. __extends(AnaglyphFreeCamera, _super);
  79950. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79951. var _this = _super.call(this, name, position, scene) || this;
  79952. _this.interaxialDistance = interaxialDistance;
  79953. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79954. return _this;
  79955. }
  79956. AnaglyphFreeCamera.prototype.getClassName = function () {
  79957. return "AnaglyphFreeCamera";
  79958. };
  79959. return AnaglyphFreeCamera;
  79960. }(BABYLON.FreeCamera));
  79961. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79962. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79963. __extends(AnaglyphArcRotateCamera, _super);
  79964. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79965. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79966. _this.interaxialDistance = interaxialDistance;
  79967. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79968. return _this;
  79969. }
  79970. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79971. return "AnaglyphArcRotateCamera";
  79972. };
  79973. return AnaglyphArcRotateCamera;
  79974. }(BABYLON.ArcRotateCamera));
  79975. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79976. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79977. __extends(AnaglyphGamepadCamera, _super);
  79978. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79979. var _this = _super.call(this, name, position, scene) || this;
  79980. _this.interaxialDistance = interaxialDistance;
  79981. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79982. return _this;
  79983. }
  79984. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79985. return "AnaglyphGamepadCamera";
  79986. };
  79987. return AnaglyphGamepadCamera;
  79988. }(BABYLON.GamepadCamera));
  79989. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79990. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79991. __extends(AnaglyphUniversalCamera, _super);
  79992. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79993. var _this = _super.call(this, name, position, scene) || this;
  79994. _this.interaxialDistance = interaxialDistance;
  79995. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79996. return _this;
  79997. }
  79998. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79999. return "AnaglyphUniversalCamera";
  80000. };
  80001. return AnaglyphUniversalCamera;
  80002. }(BABYLON.UniversalCamera));
  80003. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80004. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80005. __extends(StereoscopicFreeCamera, _super);
  80006. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80007. var _this = _super.call(this, name, position, scene) || this;
  80008. _this.interaxialDistance = interaxialDistance;
  80009. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80010. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80011. return _this;
  80012. }
  80013. StereoscopicFreeCamera.prototype.getClassName = function () {
  80014. return "StereoscopicFreeCamera";
  80015. };
  80016. return StereoscopicFreeCamera;
  80017. }(BABYLON.FreeCamera));
  80018. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80019. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80020. __extends(StereoscopicArcRotateCamera, _super);
  80021. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80022. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80023. _this.interaxialDistance = interaxialDistance;
  80024. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80025. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80026. return _this;
  80027. }
  80028. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80029. return "StereoscopicArcRotateCamera";
  80030. };
  80031. return StereoscopicArcRotateCamera;
  80032. }(BABYLON.ArcRotateCamera));
  80033. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80034. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80035. __extends(StereoscopicGamepadCamera, _super);
  80036. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80037. var _this = _super.call(this, name, position, scene) || this;
  80038. _this.interaxialDistance = interaxialDistance;
  80039. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80040. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80041. return _this;
  80042. }
  80043. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80044. return "StereoscopicGamepadCamera";
  80045. };
  80046. return StereoscopicGamepadCamera;
  80047. }(BABYLON.GamepadCamera));
  80048. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80049. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80050. __extends(StereoscopicUniversalCamera, _super);
  80051. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80052. var _this = _super.call(this, name, position, scene) || this;
  80053. _this.interaxialDistance = interaxialDistance;
  80054. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80055. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80056. return _this;
  80057. }
  80058. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80059. return "StereoscopicUniversalCamera";
  80060. };
  80061. return StereoscopicUniversalCamera;
  80062. }(BABYLON.UniversalCamera));
  80063. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80064. })(BABYLON || (BABYLON = {}));
  80065. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80066. var BABYLON;
  80067. (function (BABYLON) {
  80068. var VRExperienceHelperGazer = /** @class */ (function () {
  80069. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80070. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80071. this.scene = scene;
  80072. this._pointerDownOnMeshAsked = false;
  80073. this._isActionableMesh = false;
  80074. this._teleportationRequestInitiated = false;
  80075. this._teleportationBackRequestInitiated = false;
  80076. this._dpadPressed = true;
  80077. this._activePointer = false;
  80078. this._id = VRExperienceHelperGazer._idCounter++;
  80079. // Gaze tracker
  80080. if (!gazeTrackerToClone) {
  80081. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80082. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80083. this._gazeTracker.isPickable = false;
  80084. this._gazeTracker.isVisible = false;
  80085. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80086. targetMat.specularColor = BABYLON.Color3.Black();
  80087. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80088. targetMat.backFaceCulling = false;
  80089. this._gazeTracker.material = targetMat;
  80090. }
  80091. else {
  80092. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80093. }
  80094. }
  80095. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80096. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80097. };
  80098. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80099. this._pointerDownOnMeshAsked = true;
  80100. if (this._currentMeshSelected && this._currentHit) {
  80101. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80102. }
  80103. };
  80104. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80105. if (this._currentMeshSelected && this._currentHit) {
  80106. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80107. }
  80108. this._pointerDownOnMeshAsked = false;
  80109. };
  80110. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80111. this._activePointer = true;
  80112. };
  80113. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80114. this._activePointer = false;
  80115. };
  80116. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80117. };
  80118. VRExperienceHelperGazer.prototype.dispose = function () {
  80119. this._interactionsEnabled = false;
  80120. this._teleportationEnabled = false;
  80121. };
  80122. VRExperienceHelperGazer._idCounter = 0;
  80123. return VRExperienceHelperGazer;
  80124. }());
  80125. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80126. __extends(VRExperienceHelperControllerGazer, _super);
  80127. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80128. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80129. _this.webVRController = webVRController;
  80130. // Laser pointer
  80131. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80132. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80133. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80134. laserPointerMaterial.alpha = 0.6;
  80135. _this._laserPointer.material = laserPointerMaterial;
  80136. _this._laserPointer.rotation.x = Math.PI / 2;
  80137. _this._laserPointer.position.z = -0.5;
  80138. _this._laserPointer.isVisible = false;
  80139. if (!webVRController.mesh) {
  80140. // Create an empty mesh that is used prior to loading the high quality model
  80141. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80142. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80143. preloadPointerPose.rotation.x = -0.7;
  80144. preloadMesh.addChild(preloadPointerPose);
  80145. webVRController.attachToMesh(preloadMesh);
  80146. }
  80147. _this._setLaserPointerParent(webVRController.mesh);
  80148. return _this;
  80149. }
  80150. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80151. return this.webVRController.getForwardRay(length);
  80152. };
  80153. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80154. _super.prototype._activatePointer.call(this);
  80155. this._laserPointer.isVisible = true;
  80156. };
  80157. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80158. _super.prototype._deactivatePointer.call(this);
  80159. this._laserPointer.isVisible = false;
  80160. };
  80161. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80162. this._laserPointer.material.emissiveColor = color;
  80163. };
  80164. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80165. var makeNotPick = function (root) {
  80166. root.name += " laserPointer";
  80167. root.getChildMeshes().forEach(function (c) {
  80168. makeNotPick(c);
  80169. });
  80170. };
  80171. makeNotPick(mesh);
  80172. var childMeshes = mesh.getChildMeshes();
  80173. for (var i = 0; i < childMeshes.length; i++) {
  80174. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80175. mesh = childMeshes[i];
  80176. this.webVRController._pointingPoseNode = mesh;
  80177. break;
  80178. }
  80179. }
  80180. this._laserPointer.parent = mesh;
  80181. };
  80182. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80183. this._laserPointer.scaling.y = distance;
  80184. this._laserPointer.position.z = -distance / 2;
  80185. };
  80186. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80187. _super.prototype.dispose.call(this);
  80188. this._laserPointer.dispose();
  80189. };
  80190. return VRExperienceHelperControllerGazer;
  80191. }(VRExperienceHelperGazer));
  80192. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80193. __extends(VRExperienceHelperCameraGazer, _super);
  80194. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80195. var _this = _super.call(this, scene) || this;
  80196. _this.getCamera = getCamera;
  80197. return _this;
  80198. }
  80199. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80200. var camera = this.getCamera();
  80201. if (camera) {
  80202. return camera.getForwardRay(length);
  80203. }
  80204. else {
  80205. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80206. }
  80207. };
  80208. return VRExperienceHelperCameraGazer;
  80209. }(VRExperienceHelperGazer));
  80210. /**
  80211. * Helps to quickly add VR support to an existing scene.
  80212. * See http://doc.babylonjs.com/how_to/webvr_helper
  80213. */
  80214. var VRExperienceHelper = /** @class */ (function () {
  80215. /**
  80216. * Instantiates a VRExperienceHelper.
  80217. * Helps to quickly add VR support to an existing scene.
  80218. * @param scene The scene the VRExperienceHelper belongs to.
  80219. * @param webVROptions Options to modify the vr experience helper's behavior.
  80220. */
  80221. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80222. if (webVROptions === void 0) { webVROptions = {}; }
  80223. var _this = this;
  80224. this.webVROptions = webVROptions;
  80225. // Can the system support WebVR, even if a headset isn't plugged in?
  80226. this._webVRsupported = false;
  80227. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80228. this._webVRready = false;
  80229. // Are we waiting for the requestPresent callback to complete?
  80230. this._webVRrequesting = false;
  80231. // Are we presenting to the headset right now?
  80232. this._webVRpresenting = false;
  80233. // Are we presenting in the fullscreen fallback?
  80234. this._fullscreenVRpresenting = false;
  80235. /**
  80236. * Observable raised when entering VR.
  80237. */
  80238. this.onEnteringVRObservable = new BABYLON.Observable();
  80239. /**
  80240. * Observable raised when exiting VR.
  80241. */
  80242. this.onExitingVRObservable = new BABYLON.Observable();
  80243. /**
  80244. * Observable raised when controller mesh is loaded.
  80245. */
  80246. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80247. this._useCustomVRButton = false;
  80248. this._teleportationRequested = false;
  80249. this._teleportActive = false;
  80250. this._floorMeshesCollection = [];
  80251. this._rotationAllowed = true;
  80252. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80253. this._rotationRightAsked = false;
  80254. this._rotationLeftAsked = false;
  80255. this._isDefaultTeleportationTarget = true;
  80256. this._teleportationFillColor = "#444444";
  80257. this._teleportationBorderColor = "#FFFFFF";
  80258. this._rotationAngle = 0;
  80259. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80260. this._padSensibilityUp = 0.65;
  80261. this._padSensibilityDown = 0.35;
  80262. this.leftController = null;
  80263. this.rightController = null;
  80264. /**
  80265. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80266. */
  80267. this.onNewMeshSelected = new BABYLON.Observable();
  80268. /**
  80269. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80270. */
  80271. this.onNewMeshPicked = new BABYLON.Observable();
  80272. /**
  80273. * Observable raised before camera teleportation
  80274. */
  80275. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80276. /**
  80277. * Observable raised after camera teleportation
  80278. */
  80279. this.onAfterCameraTeleport = new BABYLON.Observable();
  80280. /**
  80281. * Observable raised when current selected mesh gets unselected
  80282. */
  80283. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80284. /**
  80285. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80286. */
  80287. this.teleportationEnabled = true;
  80288. this._teleportationInitialized = false;
  80289. this._interactionsEnabled = false;
  80290. this._interactionsRequested = false;
  80291. this._displayGaze = true;
  80292. this._displayLaserPointer = true;
  80293. this._onResize = function () {
  80294. _this.moveButtonToBottomRight();
  80295. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80296. _this.exitVR();
  80297. }
  80298. };
  80299. this._onFullscreenChange = function () {
  80300. if (document.fullscreen !== undefined) {
  80301. _this._fullscreenVRpresenting = document.fullscreen;
  80302. }
  80303. else if (document.mozFullScreen !== undefined) {
  80304. _this._fullscreenVRpresenting = document.mozFullScreen;
  80305. }
  80306. else if (document.webkitIsFullScreen !== undefined) {
  80307. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80308. }
  80309. else if (document.msIsFullScreen !== undefined) {
  80310. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80311. }
  80312. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80313. _this.exitVR();
  80314. if (!_this._useCustomVRButton) {
  80315. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80316. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80317. }
  80318. }
  80319. };
  80320. this.beforeRender = function () {
  80321. if (_this.leftController && _this.leftController._activePointer) {
  80322. _this._castRayAndSelectObject(_this.leftController);
  80323. }
  80324. if (_this.rightController && _this.rightController._activePointer) {
  80325. _this._castRayAndSelectObject(_this.rightController);
  80326. }
  80327. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80328. _this._castRayAndSelectObject(_this._cameraGazer);
  80329. }
  80330. else {
  80331. _this._cameraGazer._gazeTracker.isVisible = false;
  80332. }
  80333. };
  80334. this._onNewGamepadConnected = function (gamepad) {
  80335. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80336. if (gamepad.leftStick) {
  80337. gamepad.onleftstickchanged(function (stickValues) {
  80338. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80339. // Listening to classic/xbox gamepad only if no VR controller is active
  80340. if ((!_this.leftController && !_this.rightController) ||
  80341. ((_this.leftController && !_this.leftController._activePointer) &&
  80342. (_this.rightController && !_this.rightController._activePointer))) {
  80343. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80344. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80345. }
  80346. }
  80347. });
  80348. }
  80349. if (gamepad.rightStick) {
  80350. gamepad.onrightstickchanged(function (stickValues) {
  80351. if (_this._teleportationInitialized) {
  80352. _this._checkRotate(stickValues, _this._cameraGazer);
  80353. }
  80354. });
  80355. }
  80356. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80357. gamepad.onbuttondown(function (buttonPressed) {
  80358. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80359. _this._cameraGazer._selectionPointerDown();
  80360. }
  80361. });
  80362. gamepad.onbuttonup(function (buttonPressed) {
  80363. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80364. _this._cameraGazer._selectionPointerUp();
  80365. }
  80366. });
  80367. }
  80368. }
  80369. else {
  80370. var webVRController = gamepad;
  80371. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80372. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80373. _this.rightController = controller;
  80374. }
  80375. else {
  80376. _this.leftController = controller;
  80377. }
  80378. _this._tryEnableInteractionOnController(controller);
  80379. }
  80380. };
  80381. // 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
  80382. this._tryEnableInteractionOnController = function (controller) {
  80383. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80384. _this._enableInteractionOnController(controller);
  80385. }
  80386. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80387. _this._enableTeleportationOnController(controller);
  80388. }
  80389. };
  80390. this._onNewGamepadDisconnected = function (gamepad) {
  80391. if (gamepad instanceof BABYLON.WebVRController) {
  80392. if (gamepad.hand === "left" && _this.leftController != null) {
  80393. _this.leftController.dispose();
  80394. _this.leftController = null;
  80395. }
  80396. if (gamepad.hand === "right" && _this.rightController != null) {
  80397. _this.rightController.dispose();
  80398. _this.rightController = null;
  80399. }
  80400. }
  80401. };
  80402. this._workingVector = BABYLON.Vector3.Zero();
  80403. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80404. this._workingMatrix = BABYLON.Matrix.Identity();
  80405. this._scene = scene;
  80406. this._canvas = scene.getEngine().getRenderingCanvas();
  80407. // Parse options
  80408. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80409. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80410. }
  80411. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80412. webVROptions.createDeviceOrientationCamera = true;
  80413. }
  80414. if (webVROptions.defaultHeight === undefined) {
  80415. webVROptions.defaultHeight = 1.7;
  80416. }
  80417. if (webVROptions.useCustomVRButton) {
  80418. this._useCustomVRButton = true;
  80419. if (webVROptions.customVRButton) {
  80420. this._btnVR = webVROptions.customVRButton;
  80421. }
  80422. }
  80423. if (webVROptions.rayLength) {
  80424. this._rayLength = webVROptions.rayLength;
  80425. }
  80426. this._defaultHeight = webVROptions.defaultHeight;
  80427. if (webVROptions.positionScale) {
  80428. this._rayLength *= webVROptions.positionScale;
  80429. this._defaultHeight *= webVROptions.positionScale;
  80430. }
  80431. // Set position
  80432. if (this._scene.activeCamera) {
  80433. this._position = this._scene.activeCamera.position.clone();
  80434. }
  80435. else {
  80436. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80437. }
  80438. // Set non-vr camera
  80439. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80440. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80441. // Copy data from existing camera
  80442. if (this._scene.activeCamera) {
  80443. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80444. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80445. // Set rotation from previous camera
  80446. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80447. var targetCamera = this._scene.activeCamera;
  80448. if (targetCamera.rotationQuaternion) {
  80449. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80450. }
  80451. else {
  80452. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80453. }
  80454. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80455. }
  80456. }
  80457. this._scene.activeCamera = this._deviceOrientationCamera;
  80458. if (this._canvas) {
  80459. this._scene.activeCamera.attachControl(this._canvas);
  80460. }
  80461. }
  80462. else {
  80463. this._existingCamera = this._scene.activeCamera;
  80464. }
  80465. // Create VR cameras
  80466. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80467. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80468. }
  80469. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80470. this._webVRCamera.useStandingMatrix();
  80471. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80472. // Create default button
  80473. if (!this._useCustomVRButton) {
  80474. this._btnVR = document.createElement("BUTTON");
  80475. this._btnVR.className = "babylonVRicon";
  80476. this._btnVR.id = "babylonVRiconbtn";
  80477. this._btnVR.title = "Click to switch to VR";
  80478. 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) }";
  80479. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80480. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80481. // css += ".babylonVRicon.vrdisplaysupported { }";
  80482. // css += ".babylonVRicon.vrdisplayready { }";
  80483. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80484. var style = document.createElement('style');
  80485. style.appendChild(document.createTextNode(css));
  80486. document.getElementsByTagName('head')[0].appendChild(style);
  80487. this.moveButtonToBottomRight();
  80488. }
  80489. // VR button click event
  80490. if (this._btnVR) {
  80491. this._btnVR.addEventListener("click", function () {
  80492. if (!_this.isInVRMode) {
  80493. _this.enterVR();
  80494. }
  80495. else {
  80496. _this.exitVR();
  80497. }
  80498. });
  80499. }
  80500. // Window events
  80501. window.addEventListener("resize", this._onResize);
  80502. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80503. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80504. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80505. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80506. // Display vr button when headset is connected
  80507. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80508. this.displayVRButton();
  80509. }
  80510. else {
  80511. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80512. if (e.vrDisplay) {
  80513. _this.displayVRButton();
  80514. }
  80515. });
  80516. }
  80517. // Exiting VR mode using 'ESC' key on desktop
  80518. this._onKeyDown = function (event) {
  80519. if (event.keyCode === 27 && _this.isInVRMode) {
  80520. _this.exitVR();
  80521. }
  80522. };
  80523. document.addEventListener("keydown", this._onKeyDown);
  80524. // Exiting VR mode double tapping the touch screen
  80525. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80526. if (_this.isInVRMode) {
  80527. _this.exitVR();
  80528. if (_this._fullscreenVRpresenting) {
  80529. _this._scene.getEngine().switchFullscreen(true);
  80530. }
  80531. }
  80532. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80533. // Listen for WebVR display changes
  80534. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80535. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80536. this._onVRRequestPresentStart = function () {
  80537. _this._webVRrequesting = true;
  80538. _this.updateButtonVisibility();
  80539. };
  80540. this._onVRRequestPresentComplete = function (success) {
  80541. _this._webVRrequesting = false;
  80542. _this.updateButtonVisibility();
  80543. };
  80544. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80545. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80546. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80547. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80548. scene.onDisposeObservable.add(function () {
  80549. _this.dispose();
  80550. });
  80551. // Gamepad connection events
  80552. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80553. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80554. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80555. this.updateButtonVisibility();
  80556. //create easing functions
  80557. this._circleEase = new BABYLON.CircleEase();
  80558. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80559. }
  80560. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80561. /** Return this.onEnteringVRObservable
  80562. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80563. */
  80564. get: function () {
  80565. return this.onEnteringVRObservable;
  80566. },
  80567. enumerable: true,
  80568. configurable: true
  80569. });
  80570. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80571. /** Return this.onExitingVRObservable
  80572. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80573. */
  80574. get: function () {
  80575. return this.onExitingVRObservable;
  80576. },
  80577. enumerable: true,
  80578. configurable: true
  80579. });
  80580. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80581. /** Return this.onControllerMeshLoadedObservable
  80582. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80583. */
  80584. get: function () {
  80585. return this.onControllerMeshLoadedObservable;
  80586. },
  80587. enumerable: true,
  80588. configurable: true
  80589. });
  80590. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80591. /**
  80592. * The mesh used to display where the user is going to teleport.
  80593. */
  80594. get: function () {
  80595. return this._teleportationTarget;
  80596. },
  80597. /**
  80598. * Sets the mesh to be used to display where the user is going to teleport.
  80599. */
  80600. set: function (value) {
  80601. if (value) {
  80602. value.name = "teleportationTarget";
  80603. this._isDefaultTeleportationTarget = false;
  80604. this._teleportationTarget = value;
  80605. }
  80606. },
  80607. enumerable: true,
  80608. configurable: true
  80609. });
  80610. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80611. /**
  80612. * The mesh used to display where the user is selecting,
  80613. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80614. * See http://doc.babylonjs.com/resources/baking_transformations
  80615. */
  80616. get: function () {
  80617. return this._cameraGazer._gazeTracker;
  80618. },
  80619. set: function (value) {
  80620. if (value) {
  80621. this._cameraGazer._gazeTracker = value;
  80622. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80623. this._cameraGazer._gazeTracker.isPickable = false;
  80624. this._cameraGazer._gazeTracker.isVisible = false;
  80625. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80626. if (this.leftController) {
  80627. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80628. }
  80629. if (this.rightController) {
  80630. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80631. }
  80632. }
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80638. /**
  80639. * If the ray of the gaze should be displayed.
  80640. */
  80641. get: function () {
  80642. return this._displayGaze;
  80643. },
  80644. /**
  80645. * Sets if the ray of the gaze should be displayed.
  80646. */
  80647. set: function (value) {
  80648. this._displayGaze = value;
  80649. if (!value) {
  80650. this._cameraGazer._gazeTracker.isVisible = false;
  80651. if (this.leftController) {
  80652. this.leftController._gazeTracker.isVisible = false;
  80653. }
  80654. if (this.rightController) {
  80655. this.rightController._gazeTracker.isVisible = false;
  80656. }
  80657. }
  80658. },
  80659. enumerable: true,
  80660. configurable: true
  80661. });
  80662. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80663. /**
  80664. * If the ray of the LaserPointer should be displayed.
  80665. */
  80666. get: function () {
  80667. return this._displayLaserPointer;
  80668. },
  80669. /**
  80670. * Sets if the ray of the LaserPointer should be displayed.
  80671. */
  80672. set: function (value) {
  80673. this._displayLaserPointer = value;
  80674. if (!value) {
  80675. if (this.rightController) {
  80676. this.rightController._deactivatePointer();
  80677. this.rightController._gazeTracker.isVisible = false;
  80678. }
  80679. if (this.leftController) {
  80680. this.leftController._deactivatePointer();
  80681. this.leftController._gazeTracker.isVisible = false;
  80682. }
  80683. }
  80684. else {
  80685. if (this.rightController) {
  80686. this.rightController._activatePointer();
  80687. }
  80688. else if (this.leftController) {
  80689. this.leftController._activatePointer();
  80690. }
  80691. }
  80692. },
  80693. enumerable: true,
  80694. configurable: true
  80695. });
  80696. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80697. /**
  80698. * The deviceOrientationCamera used as the camera when not in VR.
  80699. */
  80700. get: function () {
  80701. return this._deviceOrientationCamera;
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80707. /**
  80708. * Based on the current WebVR support, returns the current VR camera used.
  80709. */
  80710. get: function () {
  80711. if (this._webVRready) {
  80712. return this._webVRCamera;
  80713. }
  80714. else {
  80715. return this._scene.activeCamera;
  80716. }
  80717. },
  80718. enumerable: true,
  80719. configurable: true
  80720. });
  80721. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80722. /**
  80723. * The webVRCamera which is used when in VR.
  80724. */
  80725. get: function () {
  80726. return this._webVRCamera;
  80727. },
  80728. enumerable: true,
  80729. configurable: true
  80730. });
  80731. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80732. /**
  80733. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80734. */
  80735. get: function () {
  80736. return this._vrDeviceOrientationCamera;
  80737. },
  80738. enumerable: true,
  80739. configurable: true
  80740. });
  80741. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80742. get: function () {
  80743. var result = this._cameraGazer._teleportationRequestInitiated
  80744. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80745. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80746. return result;
  80747. },
  80748. enumerable: true,
  80749. configurable: true
  80750. });
  80751. // Raised when one of the controller has loaded successfully its associated default mesh
  80752. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80753. if (this.leftController && this.leftController.webVRController == webVRController) {
  80754. if (webVRController.mesh) {
  80755. this.leftController._setLaserPointerParent(webVRController.mesh);
  80756. }
  80757. }
  80758. if (this.rightController && this.rightController.webVRController == webVRController) {
  80759. if (webVRController.mesh) {
  80760. this.rightController._setLaserPointerParent(webVRController.mesh);
  80761. }
  80762. }
  80763. try {
  80764. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80765. }
  80766. catch (err) {
  80767. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80768. }
  80769. };
  80770. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80771. /**
  80772. * Gets a value indicating if we are currently in VR mode.
  80773. */
  80774. get: function () {
  80775. return this._webVRpresenting || this._fullscreenVRpresenting;
  80776. },
  80777. enumerable: true,
  80778. configurable: true
  80779. });
  80780. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80781. var vrDisplay = this._scene.getEngine().getVRDevice();
  80782. if (vrDisplay) {
  80783. var wasPresenting = this._webVRpresenting;
  80784. // A VR display is connected
  80785. this._webVRpresenting = vrDisplay.isPresenting;
  80786. if (wasPresenting && !this._webVRpresenting)
  80787. this.exitVR();
  80788. }
  80789. else {
  80790. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80791. }
  80792. this.updateButtonVisibility();
  80793. };
  80794. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80795. this._webVRsupported = eventArgs.vrSupported;
  80796. this._webVRready = !!eventArgs.vrDisplay;
  80797. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80798. this.updateButtonVisibility();
  80799. };
  80800. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80801. if (this._canvas && !this._useCustomVRButton) {
  80802. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80803. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80804. }
  80805. };
  80806. VRExperienceHelper.prototype.displayVRButton = function () {
  80807. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80808. document.body.appendChild(this._btnVR);
  80809. this._btnVRDisplayed = true;
  80810. }
  80811. };
  80812. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80813. if (!this._btnVR || this._useCustomVRButton) {
  80814. return;
  80815. }
  80816. this._btnVR.className = "babylonVRicon";
  80817. if (this.isInVRMode) {
  80818. this._btnVR.className += " vrdisplaypresenting";
  80819. }
  80820. else {
  80821. if (this._webVRready)
  80822. this._btnVR.className += " vrdisplayready";
  80823. if (this._webVRsupported)
  80824. this._btnVR.className += " vrdisplaysupported";
  80825. if (this._webVRrequesting)
  80826. this._btnVR.className += " vrdisplayrequesting";
  80827. }
  80828. };
  80829. /**
  80830. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80831. * Otherwise, will use the fullscreen API.
  80832. */
  80833. VRExperienceHelper.prototype.enterVR = function () {
  80834. if (this.onEnteringVRObservable) {
  80835. try {
  80836. this.onEnteringVRObservable.notifyObservers(this);
  80837. }
  80838. catch (err) {
  80839. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80840. }
  80841. }
  80842. if (this._scene.activeCamera) {
  80843. this._position = this._scene.activeCamera.position.clone();
  80844. // make sure that we return to the last active camera
  80845. this._existingCamera = this._scene.activeCamera;
  80846. }
  80847. if (this._webVRrequesting)
  80848. return;
  80849. // If WebVR is supported and a headset is connected
  80850. if (this._webVRready) {
  80851. if (!this._webVRpresenting) {
  80852. this._webVRCamera.position = this._position;
  80853. this._scene.activeCamera = this._webVRCamera;
  80854. }
  80855. }
  80856. else if (this._vrDeviceOrientationCamera) {
  80857. this._vrDeviceOrientationCamera.position = this._position;
  80858. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80859. this._scene.getEngine().switchFullscreen(true);
  80860. this.updateButtonVisibility();
  80861. }
  80862. if (this._scene.activeCamera && this._canvas) {
  80863. this._scene.activeCamera.attachControl(this._canvas);
  80864. }
  80865. if (this._interactionsEnabled) {
  80866. this._scene.registerBeforeRender(this.beforeRender);
  80867. }
  80868. };
  80869. /**
  80870. * Attempt to exit VR, or fullscreen.
  80871. */
  80872. VRExperienceHelper.prototype.exitVR = function () {
  80873. if (this.onExitingVRObservable) {
  80874. try {
  80875. this.onExitingVRObservable.notifyObservers(this);
  80876. }
  80877. catch (err) {
  80878. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80879. }
  80880. }
  80881. if (this._webVRpresenting) {
  80882. this._scene.getEngine().disableVR();
  80883. }
  80884. if (this._scene.activeCamera) {
  80885. this._position = this._scene.activeCamera.position.clone();
  80886. }
  80887. if (this._deviceOrientationCamera) {
  80888. this._deviceOrientationCamera.position = this._position;
  80889. this._scene.activeCamera = this._deviceOrientationCamera;
  80890. if (this._canvas) {
  80891. this._scene.activeCamera.attachControl(this._canvas);
  80892. }
  80893. }
  80894. else if (this._existingCamera) {
  80895. this._existingCamera.position = this._position;
  80896. this._scene.activeCamera = this._existingCamera;
  80897. }
  80898. this.updateButtonVisibility();
  80899. if (this._interactionsEnabled) {
  80900. this._scene.unregisterBeforeRender(this.beforeRender);
  80901. }
  80902. };
  80903. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80904. /**
  80905. * The position of the vr experience helper.
  80906. */
  80907. get: function () {
  80908. return this._position;
  80909. },
  80910. /**
  80911. * Sets the position of the vr experience helper.
  80912. */
  80913. set: function (value) {
  80914. this._position = value;
  80915. if (this._scene.activeCamera) {
  80916. this._scene.activeCamera.position = value;
  80917. }
  80918. },
  80919. enumerable: true,
  80920. configurable: true
  80921. });
  80922. /**
  80923. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80924. */
  80925. VRExperienceHelper.prototype.enableInteractions = function () {
  80926. var _this = this;
  80927. if (!this._interactionsEnabled) {
  80928. this._interactionsRequested = true;
  80929. if (this.leftController) {
  80930. this._enableInteractionOnController(this.leftController);
  80931. }
  80932. if (this.rightController) {
  80933. this._enableInteractionOnController(this.rightController);
  80934. }
  80935. this.raySelectionPredicate = function (mesh) {
  80936. return mesh.isVisible;
  80937. };
  80938. this.meshSelectionPredicate = function (mesh) {
  80939. return true;
  80940. };
  80941. this._raySelectionPredicate = function (mesh) {
  80942. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80943. && mesh.name.indexOf("teleportationTarget") === -1
  80944. && mesh.name.indexOf("torusTeleportation") === -1
  80945. && mesh.name.indexOf("laserPointer") === -1)) {
  80946. return _this.raySelectionPredicate(mesh);
  80947. }
  80948. return false;
  80949. };
  80950. this._interactionsEnabled = true;
  80951. }
  80952. };
  80953. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80954. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80955. if (this._floorMeshesCollection[i].id === mesh.id) {
  80956. return true;
  80957. }
  80958. }
  80959. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80960. return true;
  80961. }
  80962. return false;
  80963. };
  80964. /**
  80965. * Adds a floor mesh to be used for teleportation.
  80966. * @param floorMesh the mesh to be used for teleportation.
  80967. */
  80968. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80969. if (!this._floorMeshesCollection) {
  80970. return;
  80971. }
  80972. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80973. return;
  80974. }
  80975. this._floorMeshesCollection.push(floorMesh);
  80976. };
  80977. /**
  80978. * Removes a floor mesh from being used for teleportation.
  80979. * @param floorMesh the mesh to be removed.
  80980. */
  80981. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80982. if (!this._floorMeshesCollection) {
  80983. return;
  80984. }
  80985. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80986. if (meshIndex !== -1) {
  80987. this._floorMeshesCollection.splice(meshIndex, 1);
  80988. }
  80989. };
  80990. /**
  80991. * Enables interactions and teleportation using the VR controllers and gaze.
  80992. * @param vrTeleportationOptions options to modify teleportation behavior.
  80993. */
  80994. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80995. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80996. if (!this._teleportationInitialized) {
  80997. this._teleportationRequested = true;
  80998. this.enableInteractions();
  80999. if (vrTeleportationOptions.floorMeshName) {
  81000. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81001. }
  81002. if (vrTeleportationOptions.floorMeshes) {
  81003. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81004. }
  81005. if (this.leftController != null) {
  81006. this._enableTeleportationOnController(this.leftController);
  81007. }
  81008. if (this.rightController != null) {
  81009. this._enableTeleportationOnController(this.rightController);
  81010. }
  81011. // Creates an image processing post process for the vignette not relying
  81012. // on the main scene configuration for image processing to reduce setup and spaces
  81013. // (gamma/linear) conflicts.
  81014. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81015. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81016. imageProcessingConfiguration.vignetteEnabled = true;
  81017. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81018. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81019. this._teleportationInitialized = true;
  81020. if (this._isDefaultTeleportationTarget) {
  81021. this._createTeleportationCircles();
  81022. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81023. }
  81024. }
  81025. };
  81026. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81027. var _this = this;
  81028. var controllerMesh = controller.webVRController.mesh;
  81029. if (controllerMesh) {
  81030. controller._interactionsEnabled = true;
  81031. controller._activatePointer();
  81032. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81033. // Enabling / disabling laserPointer
  81034. if (_this._displayLaserPointer && stateObject.value === 1) {
  81035. if (controller._activePointer) {
  81036. controller._deactivatePointer();
  81037. }
  81038. else {
  81039. controller._activatePointer();
  81040. }
  81041. if (_this.displayGaze) {
  81042. controller._gazeTracker.isVisible = controller._activePointer;
  81043. }
  81044. }
  81045. });
  81046. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81047. if (!controller._pointerDownOnMeshAsked) {
  81048. if (stateObject.value > _this._padSensibilityUp) {
  81049. controller._selectionPointerDown();
  81050. }
  81051. }
  81052. else if (stateObject.value < _this._padSensibilityDown) {
  81053. controller._selectionPointerUp();
  81054. }
  81055. });
  81056. }
  81057. };
  81058. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81059. // Dont teleport if another gaze already requested teleportation
  81060. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81061. return;
  81062. }
  81063. if (!gazer._teleportationRequestInitiated) {
  81064. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81065. gazer._activatePointer();
  81066. gazer._teleportationRequestInitiated = true;
  81067. }
  81068. }
  81069. else {
  81070. // Listening to the proper controller values changes to confirm teleportation
  81071. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81072. if (this._teleportActive) {
  81073. this._teleportCamera(this._haloCenter);
  81074. }
  81075. gazer._teleportationRequestInitiated = false;
  81076. }
  81077. }
  81078. };
  81079. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81080. // Only rotate when user is not currently selecting a teleportation location
  81081. if (gazer._teleportationRequestInitiated) {
  81082. return;
  81083. }
  81084. if (!this._rotationLeftAsked) {
  81085. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81086. this._rotationLeftAsked = true;
  81087. if (this._rotationAllowed) {
  81088. this._rotateCamera(false);
  81089. }
  81090. }
  81091. }
  81092. else {
  81093. if (stateObject.x > -this._padSensibilityDown) {
  81094. this._rotationLeftAsked = false;
  81095. }
  81096. }
  81097. if (!this._rotationRightAsked) {
  81098. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81099. this._rotationRightAsked = true;
  81100. if (this._rotationAllowed) {
  81101. this._rotateCamera(true);
  81102. }
  81103. }
  81104. }
  81105. else {
  81106. if (stateObject.x < this._padSensibilityDown) {
  81107. this._rotationRightAsked = false;
  81108. }
  81109. }
  81110. };
  81111. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81112. // Only teleport backwards when user is not currently selecting a teleportation location
  81113. if (gazer._teleportationRequestInitiated) {
  81114. return;
  81115. }
  81116. // Teleport backwards
  81117. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81118. if (!gazer._teleportationBackRequestInitiated) {
  81119. if (!this.currentVRCamera) {
  81120. return;
  81121. }
  81122. // Get rotation and position of the current camera
  81123. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81124. var position = this.currentVRCamera.position;
  81125. // If the camera has device position, use that instead
  81126. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81127. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81128. position = this.currentVRCamera.devicePosition;
  81129. }
  81130. // Get matrix with only the y rotation of the device rotation
  81131. rotation.toEulerAnglesToRef(this._workingVector);
  81132. this._workingVector.z = 0;
  81133. this._workingVector.x = 0;
  81134. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81135. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81136. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81137. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81138. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81139. var ray = new BABYLON.Ray(position, this._workingVector);
  81140. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81141. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81142. this._teleportCamera(hit.pickedPoint);
  81143. }
  81144. gazer._teleportationBackRequestInitiated = true;
  81145. }
  81146. }
  81147. else {
  81148. gazer._teleportationBackRequestInitiated = false;
  81149. }
  81150. };
  81151. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81152. var _this = this;
  81153. var controllerMesh = controller.webVRController.mesh;
  81154. if (controllerMesh) {
  81155. if (!controller._interactionsEnabled) {
  81156. this._enableInteractionOnController(controller);
  81157. }
  81158. controller._interactionsEnabled = true;
  81159. controller._teleportationEnabled = true;
  81160. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81161. controller._dpadPressed = false;
  81162. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81163. controller._dpadPressed = stateObject.pressed;
  81164. if (!controller._dpadPressed) {
  81165. _this._rotationLeftAsked = false;
  81166. _this._rotationRightAsked = false;
  81167. controller._teleportationBackRequestInitiated = false;
  81168. }
  81169. });
  81170. }
  81171. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81172. if (_this.teleportationEnabled) {
  81173. _this._checkTeleportBackwards(stateObject, controller);
  81174. _this._checkTeleportWithRay(stateObject, controller);
  81175. }
  81176. _this._checkRotate(stateObject, controller);
  81177. });
  81178. }
  81179. };
  81180. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81181. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81182. this._teleportationTarget.isPickable = false;
  81183. var length = 512;
  81184. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81185. dynamicTexture.hasAlpha = true;
  81186. var context = dynamicTexture.getContext();
  81187. var centerX = length / 2;
  81188. var centerY = length / 2;
  81189. var radius = 200;
  81190. context.beginPath();
  81191. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81192. context.fillStyle = this._teleportationFillColor;
  81193. context.fill();
  81194. context.lineWidth = 10;
  81195. context.strokeStyle = this._teleportationBorderColor;
  81196. context.stroke();
  81197. context.closePath();
  81198. dynamicTexture.update();
  81199. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81200. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81201. this._teleportationTarget.material = teleportationCircleMaterial;
  81202. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81203. torus.isPickable = false;
  81204. torus.parent = this._teleportationTarget;
  81205. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81206. var keys = [];
  81207. keys.push({
  81208. frame: 0,
  81209. value: 0
  81210. });
  81211. keys.push({
  81212. frame: 30,
  81213. value: 0.4
  81214. });
  81215. keys.push({
  81216. frame: 60,
  81217. value: 0
  81218. });
  81219. animationInnerCircle.setKeys(keys);
  81220. var easingFunction = new BABYLON.SineEase();
  81221. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81222. animationInnerCircle.setEasingFunction(easingFunction);
  81223. torus.animations = [];
  81224. torus.animations.push(animationInnerCircle);
  81225. this._scene.beginAnimation(torus, 0, 60, true);
  81226. this._hideTeleportationTarget();
  81227. };
  81228. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81229. this._teleportActive = true;
  81230. if (this._teleportationInitialized) {
  81231. this._teleportationTarget.isVisible = true;
  81232. if (this._isDefaultTeleportationTarget) {
  81233. this._teleportationTarget.getChildren()[0].isVisible = true;
  81234. }
  81235. }
  81236. };
  81237. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81238. this._teleportActive = false;
  81239. if (this._teleportationInitialized) {
  81240. this._teleportationTarget.isVisible = false;
  81241. if (this._isDefaultTeleportationTarget) {
  81242. this._teleportationTarget.getChildren()[0].isVisible = false;
  81243. }
  81244. }
  81245. };
  81246. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81247. var _this = this;
  81248. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81249. return;
  81250. }
  81251. if (right) {
  81252. this._rotationAngle++;
  81253. }
  81254. else {
  81255. this._rotationAngle--;
  81256. }
  81257. this.currentVRCamera.animations = [];
  81258. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81259. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81260. var animationRotationKeys = [];
  81261. animationRotationKeys.push({
  81262. frame: 0,
  81263. value: this.currentVRCamera.rotationQuaternion
  81264. });
  81265. animationRotationKeys.push({
  81266. frame: 6,
  81267. value: target
  81268. });
  81269. animationRotation.setKeys(animationRotationKeys);
  81270. animationRotation.setEasingFunction(this._circleEase);
  81271. this.currentVRCamera.animations.push(animationRotation);
  81272. this._postProcessMove.animations = [];
  81273. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81274. var vignetteWeightKeys = [];
  81275. vignetteWeightKeys.push({
  81276. frame: 0,
  81277. value: 0
  81278. });
  81279. vignetteWeightKeys.push({
  81280. frame: 3,
  81281. value: 4
  81282. });
  81283. vignetteWeightKeys.push({
  81284. frame: 6,
  81285. value: 0
  81286. });
  81287. animationPP.setKeys(vignetteWeightKeys);
  81288. animationPP.setEasingFunction(this._circleEase);
  81289. this._postProcessMove.animations.push(animationPP);
  81290. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81291. var vignetteStretchKeys = [];
  81292. vignetteStretchKeys.push({
  81293. frame: 0,
  81294. value: 0
  81295. });
  81296. vignetteStretchKeys.push({
  81297. frame: 3,
  81298. value: 10
  81299. });
  81300. vignetteStretchKeys.push({
  81301. frame: 6,
  81302. value: 0
  81303. });
  81304. animationPP2.setKeys(vignetteStretchKeys);
  81305. animationPP2.setEasingFunction(this._circleEase);
  81306. this._postProcessMove.animations.push(animationPP2);
  81307. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81308. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81309. this._postProcessMove.samples = 4;
  81310. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81311. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81312. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81313. });
  81314. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81315. };
  81316. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81317. if (hit.pickedPoint) {
  81318. if (gazer._teleportationRequestInitiated) {
  81319. this._displayTeleportationTarget();
  81320. this._haloCenter.copyFrom(hit.pickedPoint);
  81321. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81322. }
  81323. var pickNormal = hit.getNormal(true, false);
  81324. if (pickNormal) {
  81325. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81326. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81327. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81328. }
  81329. this._teleportationTarget.position.y += 0.1;
  81330. }
  81331. };
  81332. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81333. var _this = this;
  81334. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81335. return;
  81336. }
  81337. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81338. // offset of the headset from the anchor.
  81339. if (this.webVRCamera.leftCamera) {
  81340. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81341. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81342. location.subtractToRef(this._workingVector, this._workingVector);
  81343. }
  81344. else {
  81345. this._workingVector.copyFrom(location);
  81346. }
  81347. // Add height to account for user's height offset
  81348. if (this.isInVRMode) {
  81349. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81350. }
  81351. else {
  81352. this._workingVector.y += this._defaultHeight;
  81353. }
  81354. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81355. // Create animation from the camera's position to the new location
  81356. this.currentVRCamera.animations = [];
  81357. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81358. var animationCameraTeleportationKeys = [{
  81359. frame: 0,
  81360. value: this.currentVRCamera.position
  81361. },
  81362. {
  81363. frame: 11,
  81364. value: this._workingVector
  81365. }
  81366. ];
  81367. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81368. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81369. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81370. this._postProcessMove.animations = [];
  81371. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81372. var vignetteWeightKeys = [];
  81373. vignetteWeightKeys.push({
  81374. frame: 0,
  81375. value: 0
  81376. });
  81377. vignetteWeightKeys.push({
  81378. frame: 5,
  81379. value: 8
  81380. });
  81381. vignetteWeightKeys.push({
  81382. frame: 11,
  81383. value: 0
  81384. });
  81385. animationPP.setKeys(vignetteWeightKeys);
  81386. this._postProcessMove.animations.push(animationPP);
  81387. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81388. var vignetteStretchKeys = [];
  81389. vignetteStretchKeys.push({
  81390. frame: 0,
  81391. value: 0
  81392. });
  81393. vignetteStretchKeys.push({
  81394. frame: 5,
  81395. value: 10
  81396. });
  81397. vignetteStretchKeys.push({
  81398. frame: 11,
  81399. value: 0
  81400. });
  81401. animationPP2.setKeys(vignetteStretchKeys);
  81402. this._postProcessMove.animations.push(animationPP2);
  81403. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81404. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81405. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81406. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81407. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81408. });
  81409. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81410. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81411. });
  81412. this._hideTeleportationTarget();
  81413. };
  81414. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81415. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81416. return;
  81417. }
  81418. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81419. // Moving the gazeTracker on the mesh face targetted
  81420. if (hit && hit.pickedPoint) {
  81421. if (this._displayGaze) {
  81422. var multiplier = 1;
  81423. gazer._gazeTracker.isVisible = true;
  81424. if (gazer._isActionableMesh) {
  81425. multiplier = 3;
  81426. }
  81427. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81428. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81429. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81430. var pickNormal = hit.getNormal();
  81431. // To avoid z-fighting
  81432. var deltaFighting = 0.002;
  81433. if (pickNormal) {
  81434. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81435. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81436. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81437. }
  81438. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81439. if (gazer._gazeTracker.position.x < 0) {
  81440. gazer._gazeTracker.position.x += deltaFighting;
  81441. }
  81442. else {
  81443. gazer._gazeTracker.position.x -= deltaFighting;
  81444. }
  81445. if (gazer._gazeTracker.position.y < 0) {
  81446. gazer._gazeTracker.position.y += deltaFighting;
  81447. }
  81448. else {
  81449. gazer._gazeTracker.position.y -= deltaFighting;
  81450. }
  81451. if (gazer._gazeTracker.position.z < 0) {
  81452. gazer._gazeTracker.position.z += deltaFighting;
  81453. }
  81454. else {
  81455. gazer._gazeTracker.position.z -= deltaFighting;
  81456. }
  81457. }
  81458. // Changing the size of the laser pointer based on the distance from the targetted point
  81459. gazer._updatePointerDistance(hit.distance);
  81460. }
  81461. else {
  81462. gazer._gazeTracker.isVisible = false;
  81463. }
  81464. if (hit && hit.pickedMesh) {
  81465. gazer._currentHit = hit;
  81466. if (gazer._pointerDownOnMeshAsked) {
  81467. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81468. }
  81469. // The object selected is the floor, we're in a teleportation scenario
  81470. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81471. // Moving the teleportation area to this targetted point
  81472. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81473. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81474. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81475. }
  81476. gazer._currentMeshSelected = null;
  81477. if (gazer._teleportationRequestInitiated) {
  81478. this._moveTeleportationSelectorTo(hit, gazer);
  81479. }
  81480. return;
  81481. }
  81482. // If not, we're in a selection scenario
  81483. //this._teleportationAllowed = false;
  81484. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81485. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81486. this.onNewMeshPicked.notifyObservers(hit);
  81487. gazer._currentMeshSelected = hit.pickedMesh;
  81488. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81489. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81490. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81491. gazer._isActionableMesh = true;
  81492. }
  81493. else {
  81494. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81495. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81496. gazer._isActionableMesh = false;
  81497. }
  81498. try {
  81499. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81500. }
  81501. catch (err) {
  81502. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81503. }
  81504. }
  81505. else {
  81506. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81507. gazer._currentMeshSelected = null;
  81508. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81509. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81510. }
  81511. }
  81512. }
  81513. else {
  81514. gazer._currentHit = null;
  81515. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81516. gazer._currentMeshSelected = null;
  81517. //this._teleportationAllowed = false;
  81518. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81519. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81520. }
  81521. };
  81522. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81523. if (mesh) {
  81524. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81525. }
  81526. };
  81527. /**
  81528. * Sets the color of the laser ray from the vr controllers.
  81529. * @param color new color for the ray.
  81530. */
  81531. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81532. if (this.leftController) {
  81533. this.leftController._setLaserPointerColor(color);
  81534. }
  81535. if (this.rightController) {
  81536. this.rightController._setLaserPointerColor(color);
  81537. }
  81538. };
  81539. /**
  81540. * Sets the color of the ray from the vr headsets gaze.
  81541. * @param color new color for the ray.
  81542. */
  81543. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81544. if (!this._cameraGazer._gazeTracker.material) {
  81545. return;
  81546. }
  81547. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81548. if (this.leftController) {
  81549. this.leftController._gazeTracker.material.emissiveColor = color;
  81550. }
  81551. if (this.rightController) {
  81552. this.rightController._gazeTracker.material.emissiveColor = color;
  81553. }
  81554. };
  81555. /**
  81556. * Exits VR and disposes of the vr experience helper
  81557. */
  81558. VRExperienceHelper.prototype.dispose = function () {
  81559. if (this.isInVRMode) {
  81560. this.exitVR();
  81561. }
  81562. if (this._postProcessMove) {
  81563. this._postProcessMove.dispose();
  81564. }
  81565. if (this._webVRCamera) {
  81566. this._webVRCamera.dispose();
  81567. }
  81568. if (this._vrDeviceOrientationCamera) {
  81569. this._vrDeviceOrientationCamera.dispose();
  81570. }
  81571. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81572. document.body.removeChild(this._btnVR);
  81573. }
  81574. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81575. this._deviceOrientationCamera.dispose();
  81576. }
  81577. if (this._cameraGazer) {
  81578. this._cameraGazer.dispose();
  81579. }
  81580. if (this.leftController) {
  81581. this.leftController.dispose();
  81582. }
  81583. if (this.rightController) {
  81584. this.rightController.dispose();
  81585. }
  81586. if (this._teleportationTarget) {
  81587. this._teleportationTarget.dispose();
  81588. }
  81589. this._floorMeshesCollection = [];
  81590. document.removeEventListener("keydown", this._onKeyDown);
  81591. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81592. window.removeEventListener("resize", this._onResize);
  81593. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81594. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81595. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81596. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81597. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81598. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81599. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81600. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81601. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81602. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81603. this._scene.unregisterBeforeRender(this.beforeRender);
  81604. };
  81605. /**
  81606. * Gets the name of the VRExperienceHelper class
  81607. * @returns "VRExperienceHelper"
  81608. */
  81609. VRExperienceHelper.prototype.getClassName = function () {
  81610. return "VRExperienceHelper";
  81611. };
  81612. return VRExperienceHelper;
  81613. }());
  81614. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81615. })(BABYLON || (BABYLON = {}));
  81616. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81617. // Mainly based on these 2 articles :
  81618. // 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
  81619. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81620. var BABYLON;
  81621. (function (BABYLON) {
  81622. var JoystickAxis;
  81623. (function (JoystickAxis) {
  81624. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81625. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81626. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81627. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81628. var VirtualJoystick = /** @class */ (function () {
  81629. function VirtualJoystick(leftJoystick) {
  81630. var _this = this;
  81631. if (leftJoystick) {
  81632. this._leftJoystick = true;
  81633. }
  81634. else {
  81635. this._leftJoystick = false;
  81636. }
  81637. VirtualJoystick._globalJoystickIndex++;
  81638. // By default left & right arrow keys are moving the X
  81639. // and up & down keys are moving the Y
  81640. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81641. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81642. this.reverseLeftRight = false;
  81643. this.reverseUpDown = false;
  81644. // collections of pointers
  81645. this._touches = new BABYLON.StringDictionary();
  81646. this.deltaPosition = BABYLON.Vector3.Zero();
  81647. this._joystickSensibility = 25;
  81648. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81649. this._onResize = function (evt) {
  81650. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81651. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81652. if (VirtualJoystick.vjCanvas) {
  81653. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81654. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81655. }
  81656. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81657. };
  81658. // injecting a canvas element on top of the canvas 3D game
  81659. if (!VirtualJoystick.vjCanvas) {
  81660. window.addEventListener("resize", this._onResize, false);
  81661. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81662. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81663. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81664. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81665. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81666. VirtualJoystick.vjCanvas.style.width = "100%";
  81667. VirtualJoystick.vjCanvas.style.height = "100%";
  81668. VirtualJoystick.vjCanvas.style.position = "absolute";
  81669. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81670. VirtualJoystick.vjCanvas.style.top = "0px";
  81671. VirtualJoystick.vjCanvas.style.left = "0px";
  81672. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81673. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81674. // Support for jQuery PEP polyfill
  81675. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81676. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81677. if (!context) {
  81678. throw new Error("Unable to create canvas for virtual joystick");
  81679. }
  81680. VirtualJoystick.vjCanvasContext = context;
  81681. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81682. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81683. document.body.appendChild(VirtualJoystick.vjCanvas);
  81684. }
  81685. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81686. this.pressed = false;
  81687. // default joystick color
  81688. this._joystickColor = "cyan";
  81689. this._joystickPointerID = -1;
  81690. // current joystick position
  81691. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81692. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81693. // origin joystick position
  81694. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81695. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81696. this._onPointerDownHandlerRef = function (evt) {
  81697. _this._onPointerDown(evt);
  81698. };
  81699. this._onPointerMoveHandlerRef = function (evt) {
  81700. _this._onPointerMove(evt);
  81701. };
  81702. this._onPointerUpHandlerRef = function (evt) {
  81703. _this._onPointerUp(evt);
  81704. };
  81705. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81706. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81707. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81708. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81709. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81710. evt.preventDefault(); // Disables system menu
  81711. }, false);
  81712. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81713. }
  81714. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81715. this._joystickSensibility = newJoystickSensibility;
  81716. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81717. };
  81718. VirtualJoystick.prototype._onPointerDown = function (e) {
  81719. var positionOnScreenCondition;
  81720. e.preventDefault();
  81721. if (this._leftJoystick === true) {
  81722. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81723. }
  81724. else {
  81725. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81726. }
  81727. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81728. // First contact will be dedicated to the virtual joystick
  81729. this._joystickPointerID = e.pointerId;
  81730. this._joystickPointerStartPos.x = e.clientX;
  81731. this._joystickPointerStartPos.y = e.clientY;
  81732. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81733. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81734. this._deltaJoystickVector.x = 0;
  81735. this._deltaJoystickVector.y = 0;
  81736. this.pressed = true;
  81737. this._touches.add(e.pointerId.toString(), e);
  81738. }
  81739. else {
  81740. // You can only trigger the action buttons with a joystick declared
  81741. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81742. this._action();
  81743. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81744. }
  81745. }
  81746. };
  81747. VirtualJoystick.prototype._onPointerMove = function (e) {
  81748. // If the current pointer is the one associated to the joystick (first touch contact)
  81749. if (this._joystickPointerID == e.pointerId) {
  81750. this._joystickPointerPos.x = e.clientX;
  81751. this._joystickPointerPos.y = e.clientY;
  81752. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81753. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81754. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81755. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81756. switch (this._axisTargetedByLeftAndRight) {
  81757. case JoystickAxis.X:
  81758. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81759. break;
  81760. case JoystickAxis.Y:
  81761. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81762. break;
  81763. case JoystickAxis.Z:
  81764. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81765. break;
  81766. }
  81767. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81768. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81769. switch (this._axisTargetedByUpAndDown) {
  81770. case JoystickAxis.X:
  81771. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81772. break;
  81773. case JoystickAxis.Y:
  81774. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81775. break;
  81776. case JoystickAxis.Z:
  81777. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81778. break;
  81779. }
  81780. }
  81781. else {
  81782. var data = this._touches.get(e.pointerId.toString());
  81783. if (data) {
  81784. data.x = e.clientX;
  81785. data.y = e.clientY;
  81786. }
  81787. }
  81788. };
  81789. VirtualJoystick.prototype._onPointerUp = function (e) {
  81790. if (this._joystickPointerID == e.pointerId) {
  81791. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81792. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81793. this._joystickPointerID = -1;
  81794. this.pressed = false;
  81795. }
  81796. else {
  81797. var touch = this._touches.get(e.pointerId.toString());
  81798. if (touch) {
  81799. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81800. }
  81801. }
  81802. this._deltaJoystickVector.x = 0;
  81803. this._deltaJoystickVector.y = 0;
  81804. this._touches.remove(e.pointerId.toString());
  81805. };
  81806. /**
  81807. * Change the color of the virtual joystick
  81808. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81809. */
  81810. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81811. this._joystickColor = newColor;
  81812. };
  81813. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81814. this._action = action;
  81815. };
  81816. // Define which axis you'd like to control for left & right
  81817. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81818. switch (axis) {
  81819. case JoystickAxis.X:
  81820. case JoystickAxis.Y:
  81821. case JoystickAxis.Z:
  81822. this._axisTargetedByLeftAndRight = axis;
  81823. break;
  81824. default:
  81825. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81826. break;
  81827. }
  81828. };
  81829. // Define which axis you'd like to control for up & down
  81830. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81831. switch (axis) {
  81832. case JoystickAxis.X:
  81833. case JoystickAxis.Y:
  81834. case JoystickAxis.Z:
  81835. this._axisTargetedByUpAndDown = axis;
  81836. break;
  81837. default:
  81838. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81839. break;
  81840. }
  81841. };
  81842. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81843. var _this = this;
  81844. if (this.pressed) {
  81845. this._touches.forEach(function (key, touch) {
  81846. if (touch.pointerId === _this._joystickPointerID) {
  81847. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81848. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81849. VirtualJoystick.vjCanvasContext.beginPath();
  81850. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81851. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81852. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81853. VirtualJoystick.vjCanvasContext.stroke();
  81854. VirtualJoystick.vjCanvasContext.closePath();
  81855. VirtualJoystick.vjCanvasContext.beginPath();
  81856. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81857. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81858. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81859. VirtualJoystick.vjCanvasContext.stroke();
  81860. VirtualJoystick.vjCanvasContext.closePath();
  81861. VirtualJoystick.vjCanvasContext.beginPath();
  81862. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81863. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81864. VirtualJoystick.vjCanvasContext.stroke();
  81865. VirtualJoystick.vjCanvasContext.closePath();
  81866. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81867. }
  81868. else {
  81869. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81870. VirtualJoystick.vjCanvasContext.beginPath();
  81871. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81872. VirtualJoystick.vjCanvasContext.beginPath();
  81873. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81874. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81875. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81876. VirtualJoystick.vjCanvasContext.stroke();
  81877. VirtualJoystick.vjCanvasContext.closePath();
  81878. touch.prevX = touch.x;
  81879. touch.prevY = touch.y;
  81880. }
  81881. ;
  81882. });
  81883. }
  81884. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81885. };
  81886. VirtualJoystick.prototype.releaseCanvas = function () {
  81887. if (VirtualJoystick.vjCanvas) {
  81888. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81889. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81890. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81891. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81892. window.removeEventListener("resize", this._onResize);
  81893. document.body.removeChild(VirtualJoystick.vjCanvas);
  81894. VirtualJoystick.vjCanvas = null;
  81895. }
  81896. };
  81897. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81898. VirtualJoystick._globalJoystickIndex = 0;
  81899. return VirtualJoystick;
  81900. }());
  81901. BABYLON.VirtualJoystick = VirtualJoystick;
  81902. })(BABYLON || (BABYLON = {}));
  81903. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81904. var BABYLON;
  81905. (function (BABYLON) {
  81906. // We're mainly based on the logic defined into the FreeCamera code
  81907. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81908. __extends(VirtualJoysticksCamera, _super);
  81909. function VirtualJoysticksCamera(name, position, scene) {
  81910. var _this = _super.call(this, name, position, scene) || this;
  81911. _this.inputs.addVirtualJoystick();
  81912. return _this;
  81913. }
  81914. VirtualJoysticksCamera.prototype.getClassName = function () {
  81915. return "VirtualJoysticksCamera";
  81916. };
  81917. return VirtualJoysticksCamera;
  81918. }(BABYLON.FreeCamera));
  81919. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81920. })(BABYLON || (BABYLON = {}));
  81921. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81922. var BABYLON;
  81923. (function (BABYLON) {
  81924. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81925. function FreeCameraVirtualJoystickInput() {
  81926. }
  81927. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81928. return this._leftjoystick;
  81929. };
  81930. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81931. return this._rightjoystick;
  81932. };
  81933. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81934. if (this._leftjoystick) {
  81935. var camera = this.camera;
  81936. var speed = camera._computeLocalCameraSpeed() * 50;
  81937. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81938. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81939. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81940. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81941. if (!this._leftjoystick.pressed) {
  81942. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81943. }
  81944. if (!this._rightjoystick.pressed) {
  81945. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81946. }
  81947. }
  81948. };
  81949. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81950. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81951. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81952. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81953. this._leftjoystick.setJoystickSensibility(0.15);
  81954. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81955. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81956. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81957. this._rightjoystick.reverseUpDown = true;
  81958. this._rightjoystick.setJoystickSensibility(0.05);
  81959. this._rightjoystick.setJoystickColor("yellow");
  81960. };
  81961. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81962. this._leftjoystick.releaseCanvas();
  81963. this._rightjoystick.releaseCanvas();
  81964. };
  81965. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81966. return "FreeCameraVirtualJoystickInput";
  81967. };
  81968. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81969. return "virtualJoystick";
  81970. };
  81971. return FreeCameraVirtualJoystickInput;
  81972. }());
  81973. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81974. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81975. })(BABYLON || (BABYLON = {}));
  81976. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81977. var BABYLON;
  81978. (function (BABYLON) {
  81979. var SimplificationSettings = /** @class */ (function () {
  81980. function SimplificationSettings(quality, distance, optimizeMesh) {
  81981. this.quality = quality;
  81982. this.distance = distance;
  81983. this.optimizeMesh = optimizeMesh;
  81984. }
  81985. return SimplificationSettings;
  81986. }());
  81987. BABYLON.SimplificationSettings = SimplificationSettings;
  81988. var SimplificationQueue = /** @class */ (function () {
  81989. function SimplificationQueue() {
  81990. this.running = false;
  81991. this._simplificationArray = [];
  81992. }
  81993. SimplificationQueue.prototype.addTask = function (task) {
  81994. this._simplificationArray.push(task);
  81995. };
  81996. SimplificationQueue.prototype.executeNext = function () {
  81997. var task = this._simplificationArray.pop();
  81998. if (task) {
  81999. this.running = true;
  82000. this.runSimplification(task);
  82001. }
  82002. else {
  82003. this.running = false;
  82004. }
  82005. };
  82006. SimplificationQueue.prototype.runSimplification = function (task) {
  82007. var _this = this;
  82008. if (task.parallelProcessing) {
  82009. //parallel simplifier
  82010. task.settings.forEach(function (setting) {
  82011. var simplifier = _this.getSimplifier(task);
  82012. simplifier.simplify(setting, function (newMesh) {
  82013. task.mesh.addLODLevel(setting.distance, newMesh);
  82014. newMesh.isVisible = true;
  82015. //check if it is the last
  82016. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82017. //all done, run the success callback.
  82018. task.successCallback();
  82019. }
  82020. _this.executeNext();
  82021. });
  82022. });
  82023. }
  82024. else {
  82025. //single simplifier.
  82026. var simplifier = this.getSimplifier(task);
  82027. var runDecimation = function (setting, callback) {
  82028. simplifier.simplify(setting, function (newMesh) {
  82029. task.mesh.addLODLevel(setting.distance, newMesh);
  82030. newMesh.isVisible = true;
  82031. //run the next quality level
  82032. callback();
  82033. });
  82034. };
  82035. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82036. runDecimation(task.settings[loop.index], function () {
  82037. loop.executeNext();
  82038. });
  82039. }, function () {
  82040. //execution ended, run the success callback.
  82041. if (task.successCallback) {
  82042. task.successCallback();
  82043. }
  82044. _this.executeNext();
  82045. });
  82046. }
  82047. };
  82048. SimplificationQueue.prototype.getSimplifier = function (task) {
  82049. switch (task.simplificationType) {
  82050. case SimplificationType.QUADRATIC:
  82051. default:
  82052. return new QuadraticErrorSimplification(task.mesh);
  82053. }
  82054. };
  82055. return SimplificationQueue;
  82056. }());
  82057. BABYLON.SimplificationQueue = SimplificationQueue;
  82058. /**
  82059. * The implemented types of simplification.
  82060. * At the moment only Quadratic Error Decimation is implemented.
  82061. */
  82062. var SimplificationType;
  82063. (function (SimplificationType) {
  82064. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82065. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82066. var DecimationTriangle = /** @class */ (function () {
  82067. function DecimationTriangle(vertices) {
  82068. this.vertices = vertices;
  82069. this.error = new Array(4);
  82070. this.deleted = false;
  82071. this.isDirty = false;
  82072. this.deletePending = false;
  82073. this.borderFactor = 0;
  82074. }
  82075. return DecimationTriangle;
  82076. }());
  82077. BABYLON.DecimationTriangle = DecimationTriangle;
  82078. var DecimationVertex = /** @class */ (function () {
  82079. function DecimationVertex(position, id) {
  82080. this.position = position;
  82081. this.id = id;
  82082. this.isBorder = true;
  82083. this.q = new QuadraticMatrix();
  82084. this.triangleCount = 0;
  82085. this.triangleStart = 0;
  82086. this.originalOffsets = [];
  82087. }
  82088. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82089. this.position.copyFrom(newPosition);
  82090. };
  82091. return DecimationVertex;
  82092. }());
  82093. BABYLON.DecimationVertex = DecimationVertex;
  82094. var QuadraticMatrix = /** @class */ (function () {
  82095. function QuadraticMatrix(data) {
  82096. this.data = new Array(10);
  82097. for (var i = 0; i < 10; ++i) {
  82098. if (data && data[i]) {
  82099. this.data[i] = data[i];
  82100. }
  82101. else {
  82102. this.data[i] = 0;
  82103. }
  82104. }
  82105. }
  82106. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82107. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82108. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82109. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82110. return det;
  82111. };
  82112. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82113. for (var i = 0; i < 10; ++i) {
  82114. this.data[i] += matrix.data[i];
  82115. }
  82116. };
  82117. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82118. for (var i = 0; i < 10; ++i) {
  82119. this.data[i] += data[i];
  82120. }
  82121. };
  82122. QuadraticMatrix.prototype.add = function (matrix) {
  82123. var m = new QuadraticMatrix();
  82124. for (var i = 0; i < 10; ++i) {
  82125. m.data[i] = this.data[i] + matrix.data[i];
  82126. }
  82127. return m;
  82128. };
  82129. QuadraticMatrix.FromData = function (a, b, c, d) {
  82130. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82131. };
  82132. //returning an array to avoid garbage collection
  82133. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82134. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82135. };
  82136. return QuadraticMatrix;
  82137. }());
  82138. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82139. var Reference = /** @class */ (function () {
  82140. function Reference(vertexId, triangleId) {
  82141. this.vertexId = vertexId;
  82142. this.triangleId = triangleId;
  82143. }
  82144. return Reference;
  82145. }());
  82146. BABYLON.Reference = Reference;
  82147. /**
  82148. * An implementation of the Quadratic Error simplification algorithm.
  82149. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82150. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82151. * @author RaananW
  82152. */
  82153. var QuadraticErrorSimplification = /** @class */ (function () {
  82154. function QuadraticErrorSimplification(_mesh) {
  82155. this._mesh = _mesh;
  82156. this.syncIterations = 5000;
  82157. this.aggressiveness = 7;
  82158. this.decimationIterations = 100;
  82159. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82160. }
  82161. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82162. var _this = this;
  82163. this.initDecimatedMesh();
  82164. //iterating through the submeshes array, one after the other.
  82165. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82166. _this.initWithMesh(loop.index, function () {
  82167. _this.runDecimation(settings, loop.index, function () {
  82168. loop.executeNext();
  82169. });
  82170. }, settings.optimizeMesh);
  82171. }, function () {
  82172. setTimeout(function () {
  82173. successCallback(_this._reconstructedMesh);
  82174. }, 0);
  82175. });
  82176. };
  82177. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82178. var _this = this;
  82179. var targetCount = ~~(this.triangles.length * settings.quality);
  82180. var deletedTriangles = 0;
  82181. var triangleCount = this.triangles.length;
  82182. var iterationFunction = function (iteration, callback) {
  82183. setTimeout(function () {
  82184. if (iteration % 5 === 0) {
  82185. _this.updateMesh(iteration === 0);
  82186. }
  82187. for (var i = 0; i < _this.triangles.length; ++i) {
  82188. _this.triangles[i].isDirty = false;
  82189. }
  82190. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82191. var trianglesIterator = function (i) {
  82192. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82193. var t = _this.triangles[tIdx];
  82194. if (!t)
  82195. return;
  82196. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82197. return;
  82198. }
  82199. for (var j = 0; j < 3; ++j) {
  82200. if (t.error[j] < threshold) {
  82201. var deleted0 = [];
  82202. var deleted1 = [];
  82203. var v0 = t.vertices[j];
  82204. var v1 = t.vertices[(j + 1) % 3];
  82205. if (v0.isBorder || v1.isBorder)
  82206. continue;
  82207. var p = BABYLON.Vector3.Zero();
  82208. var n = BABYLON.Vector3.Zero();
  82209. var uv = BABYLON.Vector2.Zero();
  82210. var color = new BABYLON.Color4(0, 0, 0, 1);
  82211. _this.calculateError(v0, v1, p, n, uv, color);
  82212. var delTr = new Array();
  82213. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82214. continue;
  82215. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82216. continue;
  82217. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82218. continue;
  82219. var uniqueArray = new Array();
  82220. delTr.forEach(function (deletedT) {
  82221. if (uniqueArray.indexOf(deletedT) === -1) {
  82222. deletedT.deletePending = true;
  82223. uniqueArray.push(deletedT);
  82224. }
  82225. });
  82226. if (uniqueArray.length % 2 !== 0) {
  82227. continue;
  82228. }
  82229. v0.q = v1.q.add(v0.q);
  82230. v0.updatePosition(p);
  82231. var tStart = _this.references.length;
  82232. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82233. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82234. var tCount = _this.references.length - tStart;
  82235. if (tCount <= v0.triangleCount) {
  82236. if (tCount) {
  82237. for (var c = 0; c < tCount; c++) {
  82238. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82239. }
  82240. }
  82241. }
  82242. else {
  82243. v0.triangleStart = tStart;
  82244. }
  82245. v0.triangleCount = tCount;
  82246. break;
  82247. }
  82248. }
  82249. };
  82250. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82251. }, 0);
  82252. };
  82253. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82254. if (triangleCount - deletedTriangles <= targetCount)
  82255. loop.breakLoop();
  82256. else {
  82257. iterationFunction(loop.index, function () {
  82258. loop.executeNext();
  82259. });
  82260. }
  82261. }, function () {
  82262. setTimeout(function () {
  82263. //reconstruct this part of the mesh
  82264. _this.reconstructMesh(submeshIndex);
  82265. successCallback();
  82266. }, 0);
  82267. });
  82268. };
  82269. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82270. var _this = this;
  82271. this.vertices = [];
  82272. this.triangles = [];
  82273. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82274. var indices = this._mesh.getIndices();
  82275. var submesh = this._mesh.subMeshes[submeshIndex];
  82276. var findInVertices = function (positionToSearch) {
  82277. if (optimizeMesh) {
  82278. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82279. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82280. return _this.vertices[ii];
  82281. }
  82282. }
  82283. }
  82284. return null;
  82285. };
  82286. var vertexReferences = [];
  82287. var vertexInit = function (i) {
  82288. if (!positionData) {
  82289. return;
  82290. }
  82291. var offset = i + submesh.verticesStart;
  82292. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82293. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82294. vertex.originalOffsets.push(offset);
  82295. if (vertex.id === _this.vertices.length) {
  82296. _this.vertices.push(vertex);
  82297. }
  82298. vertexReferences.push(vertex.id);
  82299. };
  82300. //var totalVertices = mesh.getTotalVertices();
  82301. var totalVertices = submesh.verticesCount;
  82302. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82303. var indicesInit = function (i) {
  82304. if (!indices) {
  82305. return;
  82306. }
  82307. var offset = (submesh.indexStart / 3) + i;
  82308. var pos = (offset * 3);
  82309. var i0 = indices[pos + 0];
  82310. var i1 = indices[pos + 1];
  82311. var i2 = indices[pos + 2];
  82312. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82313. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82314. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82315. var triangle = new DecimationTriangle([v0, v1, v2]);
  82316. triangle.originalOffset = pos;
  82317. _this.triangles.push(triangle);
  82318. };
  82319. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82320. _this.init(callback);
  82321. });
  82322. });
  82323. };
  82324. QuadraticErrorSimplification.prototype.init = function (callback) {
  82325. var _this = this;
  82326. var triangleInit1 = function (i) {
  82327. var t = _this.triangles[i];
  82328. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82329. for (var j = 0; j < 3; j++) {
  82330. 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))));
  82331. }
  82332. };
  82333. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82334. var triangleInit2 = function (i) {
  82335. var t = _this.triangles[i];
  82336. for (var j = 0; j < 3; ++j) {
  82337. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82338. }
  82339. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82340. };
  82341. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82342. callback();
  82343. });
  82344. });
  82345. };
  82346. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82347. var newTriangles = [];
  82348. var i;
  82349. for (i = 0; i < this.vertices.length; ++i) {
  82350. this.vertices[i].triangleCount = 0;
  82351. }
  82352. var t;
  82353. var j;
  82354. for (i = 0; i < this.triangles.length; ++i) {
  82355. if (!this.triangles[i].deleted) {
  82356. t = this.triangles[i];
  82357. for (j = 0; j < 3; ++j) {
  82358. t.vertices[j].triangleCount = 1;
  82359. }
  82360. newTriangles.push(t);
  82361. }
  82362. }
  82363. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82364. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82365. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82366. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82367. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82368. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82369. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82370. var vertexCount = 0;
  82371. for (i = 0; i < this.vertices.length; ++i) {
  82372. var vertex = this.vertices[i];
  82373. vertex.id = vertexCount;
  82374. if (vertex.triangleCount) {
  82375. vertex.originalOffsets.forEach(function (originalOffset) {
  82376. if (!normalData) {
  82377. return;
  82378. }
  82379. newPositionData.push(vertex.position.x);
  82380. newPositionData.push(vertex.position.y);
  82381. newPositionData.push(vertex.position.z);
  82382. newNormalData.push(normalData[originalOffset * 3]);
  82383. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82384. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82385. if (uvs && uvs.length) {
  82386. newUVsData.push(uvs[(originalOffset * 2)]);
  82387. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82388. }
  82389. else if (colorsData && colorsData.length) {
  82390. newColorsData.push(colorsData[(originalOffset * 4)]);
  82391. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82392. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82393. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82394. }
  82395. ++vertexCount;
  82396. });
  82397. }
  82398. }
  82399. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82400. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82401. var submeshesArray = this._reconstructedMesh.subMeshes;
  82402. this._reconstructedMesh.subMeshes = [];
  82403. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82404. var originalIndices = this._mesh.getIndices();
  82405. for (i = 0; i < newTriangles.length; ++i) {
  82406. t = newTriangles[i]; //now get the new referencing point for each vertex
  82407. [0, 1, 2].forEach(function (idx) {
  82408. var id = originalIndices[t.originalOffset + idx];
  82409. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82410. if (offset < 0)
  82411. offset = 0;
  82412. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82413. });
  82414. }
  82415. //overwriting the old vertex buffers and indices.
  82416. this._reconstructedMesh.setIndices(newIndicesArray);
  82417. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82418. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82419. if (newUVsData.length > 0)
  82420. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82421. if (newColorsData.length > 0)
  82422. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82423. //create submesh
  82424. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82425. if (submeshIndex > 0) {
  82426. this._reconstructedMesh.subMeshes = [];
  82427. submeshesArray.forEach(function (submesh) {
  82428. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82429. });
  82430. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82431. }
  82432. };
  82433. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82434. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82435. this._reconstructedMesh.material = this._mesh.material;
  82436. this._reconstructedMesh.parent = this._mesh.parent;
  82437. this._reconstructedMesh.isVisible = false;
  82438. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82439. };
  82440. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82441. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82442. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82443. if (t.deleted)
  82444. continue;
  82445. var s = this.references[vertex1.triangleStart + i].vertexId;
  82446. var v1 = t.vertices[(s + 1) % 3];
  82447. var v2 = t.vertices[(s + 2) % 3];
  82448. if ((v1 === vertex2 || v2 === vertex2)) {
  82449. deletedArray[i] = true;
  82450. delTr.push(t);
  82451. continue;
  82452. }
  82453. var d1 = v1.position.subtract(point);
  82454. d1 = d1.normalize();
  82455. var d2 = v2.position.subtract(point);
  82456. d2 = d2.normalize();
  82457. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82458. return true;
  82459. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82460. deletedArray[i] = false;
  82461. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82462. return true;
  82463. }
  82464. return false;
  82465. };
  82466. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82467. var newDeleted = deletedTriangles;
  82468. for (var i = 0; i < vertex.triangleCount; ++i) {
  82469. var ref = this.references[vertex.triangleStart + i];
  82470. var t = this.triangles[ref.triangleId];
  82471. if (t.deleted)
  82472. continue;
  82473. if (deletedArray[i] && t.deletePending) {
  82474. t.deleted = true;
  82475. newDeleted++;
  82476. continue;
  82477. }
  82478. t.vertices[ref.vertexId] = origVertex;
  82479. t.isDirty = true;
  82480. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82481. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82482. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82483. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82484. this.references.push(ref);
  82485. }
  82486. return newDeleted;
  82487. };
  82488. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82489. for (var i = 0; i < this.vertices.length; ++i) {
  82490. var vCount = [];
  82491. var vId = [];
  82492. var v = this.vertices[i];
  82493. var j;
  82494. for (j = 0; j < v.triangleCount; ++j) {
  82495. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82496. for (var ii = 0; ii < 3; ii++) {
  82497. var ofs = 0;
  82498. var vv = triangle.vertices[ii];
  82499. while (ofs < vCount.length) {
  82500. if (vId[ofs] === vv.id)
  82501. break;
  82502. ++ofs;
  82503. }
  82504. if (ofs === vCount.length) {
  82505. vCount.push(1);
  82506. vId.push(vv.id);
  82507. }
  82508. else {
  82509. vCount[ofs]++;
  82510. }
  82511. }
  82512. }
  82513. for (j = 0; j < vCount.length; ++j) {
  82514. if (vCount[j] === 1) {
  82515. this.vertices[vId[j]].isBorder = true;
  82516. }
  82517. else {
  82518. this.vertices[vId[j]].isBorder = false;
  82519. }
  82520. }
  82521. }
  82522. };
  82523. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82524. if (identifyBorders === void 0) { identifyBorders = false; }
  82525. var i;
  82526. if (!identifyBorders) {
  82527. var newTrianglesVector = [];
  82528. for (i = 0; i < this.triangles.length; ++i) {
  82529. if (!this.triangles[i].deleted) {
  82530. newTrianglesVector.push(this.triangles[i]);
  82531. }
  82532. }
  82533. this.triangles = newTrianglesVector;
  82534. }
  82535. for (i = 0; i < this.vertices.length; ++i) {
  82536. this.vertices[i].triangleCount = 0;
  82537. this.vertices[i].triangleStart = 0;
  82538. }
  82539. var t;
  82540. var j;
  82541. var v;
  82542. for (i = 0; i < this.triangles.length; ++i) {
  82543. t = this.triangles[i];
  82544. for (j = 0; j < 3; ++j) {
  82545. v = t.vertices[j];
  82546. v.triangleCount++;
  82547. }
  82548. }
  82549. var tStart = 0;
  82550. for (i = 0; i < this.vertices.length; ++i) {
  82551. this.vertices[i].triangleStart = tStart;
  82552. tStart += this.vertices[i].triangleCount;
  82553. this.vertices[i].triangleCount = 0;
  82554. }
  82555. var newReferences = new Array(this.triangles.length * 3);
  82556. for (i = 0; i < this.triangles.length; ++i) {
  82557. t = this.triangles[i];
  82558. for (j = 0; j < 3; ++j) {
  82559. v = t.vertices[j];
  82560. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82561. v.triangleCount++;
  82562. }
  82563. }
  82564. this.references = newReferences;
  82565. if (identifyBorders) {
  82566. this.identifyBorder();
  82567. }
  82568. };
  82569. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82570. var x = point.x;
  82571. var y = point.y;
  82572. var z = point.z;
  82573. 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
  82574. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82575. };
  82576. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82577. var q = vertex1.q.add(vertex2.q);
  82578. var border = vertex1.isBorder && vertex2.isBorder;
  82579. var error = 0;
  82580. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82581. if (qDet !== 0 && !border) {
  82582. if (!pointResult) {
  82583. pointResult = BABYLON.Vector3.Zero();
  82584. }
  82585. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82586. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82587. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82588. error = this.vertexError(q, pointResult);
  82589. }
  82590. else {
  82591. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82592. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82593. var error1 = this.vertexError(q, vertex1.position);
  82594. var error2 = this.vertexError(q, vertex2.position);
  82595. var error3 = this.vertexError(q, p3);
  82596. error = Math.min(error1, error2, error3);
  82597. if (error === error1) {
  82598. if (pointResult) {
  82599. pointResult.copyFrom(vertex1.position);
  82600. }
  82601. }
  82602. else if (error === error2) {
  82603. if (pointResult) {
  82604. pointResult.copyFrom(vertex2.position);
  82605. }
  82606. }
  82607. else {
  82608. if (pointResult) {
  82609. pointResult.copyFrom(p3);
  82610. }
  82611. }
  82612. }
  82613. return error;
  82614. };
  82615. return QuadraticErrorSimplification;
  82616. }());
  82617. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82618. })(BABYLON || (BABYLON = {}));
  82619. //# sourceMappingURL=babylon.meshSimplification.js.map
  82620. var BABYLON;
  82621. (function (BABYLON) {
  82622. var MeshLODLevel = /** @class */ (function () {
  82623. function MeshLODLevel(distance, mesh) {
  82624. this.distance = distance;
  82625. this.mesh = mesh;
  82626. }
  82627. return MeshLODLevel;
  82628. }());
  82629. BABYLON.MeshLODLevel = MeshLODLevel;
  82630. })(BABYLON || (BABYLON = {}));
  82631. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82632. var BABYLON;
  82633. (function (BABYLON) {
  82634. /**
  82635. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82637. */
  82638. var SceneOptimization = /** @class */ (function () {
  82639. /**
  82640. * Creates the SceneOptimization object
  82641. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82642. * @param desc defines the description associated with the optimization
  82643. */
  82644. function SceneOptimization(
  82645. /**
  82646. * Defines the priority of this optimization (0 by default which means first in the list)
  82647. */
  82648. priority) {
  82649. if (priority === void 0) { priority = 0; }
  82650. this.priority = priority;
  82651. }
  82652. /**
  82653. * Gets a string describing the action executed by the current optimization
  82654. * @returns description string
  82655. */
  82656. SceneOptimization.prototype.getDescription = function () {
  82657. return "";
  82658. };
  82659. /**
  82660. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82661. * @param scene defines the current scene where to apply this optimization
  82662. * @param optimizer defines the current optimizer
  82663. * @returns true if everything that can be done was applied
  82664. */
  82665. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82666. return true;
  82667. };
  82668. ;
  82669. return SceneOptimization;
  82670. }());
  82671. BABYLON.SceneOptimization = SceneOptimization;
  82672. /**
  82673. * Defines an optimization used to reduce the size of render target textures
  82674. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82675. */
  82676. var TextureOptimization = /** @class */ (function (_super) {
  82677. __extends(TextureOptimization, _super);
  82678. /**
  82679. * Creates the TextureOptimization object
  82680. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82681. * @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
  82682. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82683. */
  82684. function TextureOptimization(
  82685. /**
  82686. * Defines the priority of this optimization (0 by default which means first in the list)
  82687. */
  82688. priority,
  82689. /**
  82690. * 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
  82691. */
  82692. maximumSize,
  82693. /**
  82694. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82695. */
  82696. step) {
  82697. if (priority === void 0) { priority = 0; }
  82698. if (maximumSize === void 0) { maximumSize = 1024; }
  82699. if (step === void 0) { step = 0.5; }
  82700. var _this = _super.call(this, priority) || this;
  82701. _this.priority = priority;
  82702. _this.maximumSize = maximumSize;
  82703. _this.step = step;
  82704. return _this;
  82705. }
  82706. /**
  82707. * Gets a string describing the action executed by the current optimization
  82708. * @returns description string
  82709. */
  82710. TextureOptimization.prototype.getDescription = function () {
  82711. return "Reducing render target texture size to " + this.maximumSize;
  82712. };
  82713. /**
  82714. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82715. * @param scene defines the current scene where to apply this optimization
  82716. * @param optimizer defines the current optimizer
  82717. * @returns true if everything that can be done was applied
  82718. */
  82719. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82720. var allDone = true;
  82721. for (var index = 0; index < scene.textures.length; index++) {
  82722. var texture = scene.textures[index];
  82723. if (!texture.canRescale || texture.getContext) {
  82724. continue;
  82725. }
  82726. var currentSize = texture.getSize();
  82727. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82728. if (maxDimension > this.maximumSize) {
  82729. texture.scale(this.step);
  82730. allDone = false;
  82731. }
  82732. }
  82733. return allDone;
  82734. };
  82735. return TextureOptimization;
  82736. }(SceneOptimization));
  82737. BABYLON.TextureOptimization = TextureOptimization;
  82738. /**
  82739. * Defines an optimization used to increase or decrease the rendering resolution
  82740. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82741. */
  82742. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82743. __extends(HardwareScalingOptimization, _super);
  82744. /**
  82745. * Creates the HardwareScalingOptimization object
  82746. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82747. * @param maximumScale defines the maximum scale to use (2 by default)
  82748. * @param step defines the step to use between two passes (0.5 by default)
  82749. */
  82750. function HardwareScalingOptimization(
  82751. /**
  82752. * Defines the priority of this optimization (0 by default which means first in the list)
  82753. */
  82754. priority,
  82755. /**
  82756. * Defines the maximum scale to use (2 by default)
  82757. */
  82758. maximumScale,
  82759. /**
  82760. * Defines the step to use between two passes (0.5 by default)
  82761. */
  82762. step) {
  82763. if (priority === void 0) { priority = 0; }
  82764. if (maximumScale === void 0) { maximumScale = 2; }
  82765. if (step === void 0) { step = 0.25; }
  82766. var _this = _super.call(this, priority) || this;
  82767. _this.priority = priority;
  82768. _this.maximumScale = maximumScale;
  82769. _this.step = step;
  82770. _this._currentScale = -1;
  82771. _this._directionOffset = 1;
  82772. return _this;
  82773. }
  82774. /**
  82775. * Gets a string describing the action executed by the current optimization
  82776. * @return description string
  82777. */
  82778. HardwareScalingOptimization.prototype.getDescription = function () {
  82779. return "Setting hardware scaling level to " + this._currentScale;
  82780. };
  82781. /**
  82782. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82783. * @param scene defines the current scene where to apply this optimization
  82784. * @param optimizer defines the current optimizer
  82785. * @returns true if everything that can be done was applied
  82786. */
  82787. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82788. if (this._currentScale === -1) {
  82789. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82790. if (this._currentScale > this.maximumScale) {
  82791. this._directionOffset = -1;
  82792. }
  82793. }
  82794. this._currentScale += this._directionOffset * this.step;
  82795. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82796. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82797. };
  82798. ;
  82799. return HardwareScalingOptimization;
  82800. }(SceneOptimization));
  82801. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82802. /**
  82803. * Defines an optimization used to remove shadows
  82804. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82805. */
  82806. var ShadowsOptimization = /** @class */ (function (_super) {
  82807. __extends(ShadowsOptimization, _super);
  82808. function ShadowsOptimization() {
  82809. return _super !== null && _super.apply(this, arguments) || this;
  82810. }
  82811. /**
  82812. * Gets a string describing the action executed by the current optimization
  82813. * @return description string
  82814. */
  82815. ShadowsOptimization.prototype.getDescription = function () {
  82816. return "Turning shadows on/off";
  82817. };
  82818. /**
  82819. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82820. * @param scene defines the current scene where to apply this optimization
  82821. * @param optimizer defines the current optimizer
  82822. * @returns true if everything that can be done was applied
  82823. */
  82824. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82825. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82826. return true;
  82827. };
  82828. ;
  82829. return ShadowsOptimization;
  82830. }(SceneOptimization));
  82831. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82832. /**
  82833. * Defines an optimization used to turn post-processes off
  82834. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82835. */
  82836. var PostProcessesOptimization = /** @class */ (function (_super) {
  82837. __extends(PostProcessesOptimization, _super);
  82838. function PostProcessesOptimization() {
  82839. return _super !== null && _super.apply(this, arguments) || this;
  82840. }
  82841. /**
  82842. * Gets a string describing the action executed by the current optimization
  82843. * @return description string
  82844. */
  82845. PostProcessesOptimization.prototype.getDescription = function () {
  82846. return "Turning post-processes on/off";
  82847. };
  82848. /**
  82849. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82850. * @param scene defines the current scene where to apply this optimization
  82851. * @param optimizer defines the current optimizer
  82852. * @returns true if everything that can be done was applied
  82853. */
  82854. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82855. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82856. return true;
  82857. };
  82858. ;
  82859. return PostProcessesOptimization;
  82860. }(SceneOptimization));
  82861. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82862. /**
  82863. * Defines an optimization used to turn lens flares off
  82864. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82865. */
  82866. var LensFlaresOptimization = /** @class */ (function (_super) {
  82867. __extends(LensFlaresOptimization, _super);
  82868. function LensFlaresOptimization() {
  82869. return _super !== null && _super.apply(this, arguments) || this;
  82870. }
  82871. /**
  82872. * Gets a string describing the action executed by the current optimization
  82873. * @return description string
  82874. */
  82875. LensFlaresOptimization.prototype.getDescription = function () {
  82876. return "Turning lens flares on/off";
  82877. };
  82878. /**
  82879. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82880. * @param scene defines the current scene where to apply this optimization
  82881. * @param optimizer defines the current optimizer
  82882. * @returns true if everything that can be done was applied
  82883. */
  82884. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82885. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82886. return true;
  82887. };
  82888. ;
  82889. return LensFlaresOptimization;
  82890. }(SceneOptimization));
  82891. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82892. /**
  82893. * Defines an optimization based on user defined callback.
  82894. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82895. */
  82896. var CustomOptimization = /** @class */ (function (_super) {
  82897. __extends(CustomOptimization, _super);
  82898. function CustomOptimization() {
  82899. return _super !== null && _super.apply(this, arguments) || this;
  82900. }
  82901. /**
  82902. * Gets a string describing the action executed by the current optimization
  82903. * @returns description string
  82904. */
  82905. CustomOptimization.prototype.getDescription = function () {
  82906. if (this.onGetDescription) {
  82907. return this.onGetDescription();
  82908. }
  82909. return "Running user defined callback";
  82910. };
  82911. /**
  82912. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82913. * @param scene defines the current scene where to apply this optimization
  82914. * @param optimizer defines the current optimizer
  82915. * @returns true if everything that can be done was applied
  82916. */
  82917. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82918. if (this.onApply) {
  82919. return this.onApply(scene, optimizer);
  82920. }
  82921. return true;
  82922. };
  82923. ;
  82924. return CustomOptimization;
  82925. }(SceneOptimization));
  82926. BABYLON.CustomOptimization = CustomOptimization;
  82927. /**
  82928. * Defines an optimization used to turn particles off
  82929. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82930. */
  82931. var ParticlesOptimization = /** @class */ (function (_super) {
  82932. __extends(ParticlesOptimization, _super);
  82933. function ParticlesOptimization() {
  82934. return _super !== null && _super.apply(this, arguments) || this;
  82935. }
  82936. /**
  82937. * Gets a string describing the action executed by the current optimization
  82938. * @return description string
  82939. */
  82940. ParticlesOptimization.prototype.getDescription = function () {
  82941. return "Turning particles on/off";
  82942. };
  82943. /**
  82944. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82945. * @param scene defines the current scene where to apply this optimization
  82946. * @param optimizer defines the current optimizer
  82947. * @returns true if everything that can be done was applied
  82948. */
  82949. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82950. scene.particlesEnabled = optimizer.isInImprovementMode;
  82951. return true;
  82952. };
  82953. ;
  82954. return ParticlesOptimization;
  82955. }(SceneOptimization));
  82956. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82957. /**
  82958. * Defines an optimization used to turn render targets off
  82959. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82960. */
  82961. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82962. __extends(RenderTargetsOptimization, _super);
  82963. function RenderTargetsOptimization() {
  82964. return _super !== null && _super.apply(this, arguments) || this;
  82965. }
  82966. /**
  82967. * Gets a string describing the action executed by the current optimization
  82968. * @return description string
  82969. */
  82970. RenderTargetsOptimization.prototype.getDescription = function () {
  82971. return "Turning render targets off";
  82972. };
  82973. /**
  82974. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82975. * @param scene defines the current scene where to apply this optimization
  82976. * @param optimizer defines the current optimizer
  82977. * @returns true if everything that can be done was applied
  82978. */
  82979. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82980. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82981. return true;
  82982. };
  82983. ;
  82984. return RenderTargetsOptimization;
  82985. }(SceneOptimization));
  82986. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82987. /**
  82988. * Defines an optimization used to merge meshes with compatible materials
  82989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82990. */
  82991. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82992. __extends(MergeMeshesOptimization, _super);
  82993. function MergeMeshesOptimization() {
  82994. var _this = _super !== null && _super.apply(this, arguments) || this;
  82995. _this._canBeMerged = function (abstractMesh) {
  82996. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82997. return false;
  82998. }
  82999. var mesh = abstractMesh;
  83000. if (!mesh.isVisible || !mesh.isEnabled()) {
  83001. return false;
  83002. }
  83003. if (mesh.instances.length > 0) {
  83004. return false;
  83005. }
  83006. if (mesh.skeleton || mesh.hasLODLevels) {
  83007. return false;
  83008. }
  83009. if (mesh.parent) {
  83010. return false;
  83011. }
  83012. return true;
  83013. };
  83014. return _this;
  83015. }
  83016. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83017. /**
  83018. * Gets or sets a boolean which defines if optimization octree has to be updated
  83019. */
  83020. get: function () {
  83021. return MergeMeshesOptimization._UpdateSelectionTree;
  83022. },
  83023. /**
  83024. * Gets or sets a boolean which defines if optimization octree has to be updated
  83025. */
  83026. set: function (value) {
  83027. MergeMeshesOptimization._UpdateSelectionTree = value;
  83028. },
  83029. enumerable: true,
  83030. configurable: true
  83031. });
  83032. /**
  83033. * Gets a string describing the action executed by the current optimization
  83034. * @return description string
  83035. */
  83036. MergeMeshesOptimization.prototype.getDescription = function () {
  83037. return "Merging similar meshes together";
  83038. };
  83039. /**
  83040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83041. * @param scene defines the current scene where to apply this optimization
  83042. * @param optimizer defines the current optimizer
  83043. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83044. * @returns true if everything that can be done was applied
  83045. */
  83046. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83047. var globalPool = scene.meshes.slice(0);
  83048. var globalLength = globalPool.length;
  83049. for (var index = 0; index < globalLength; index++) {
  83050. var currentPool = new Array();
  83051. var current = globalPool[index];
  83052. // Checks
  83053. if (!this._canBeMerged(current)) {
  83054. continue;
  83055. }
  83056. currentPool.push(current);
  83057. // Find compatible meshes
  83058. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83059. var otherMesh = globalPool[subIndex];
  83060. if (!this._canBeMerged(otherMesh)) {
  83061. continue;
  83062. }
  83063. if (otherMesh.material !== current.material) {
  83064. continue;
  83065. }
  83066. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83067. continue;
  83068. }
  83069. currentPool.push(otherMesh);
  83070. globalLength--;
  83071. globalPool.splice(subIndex, 1);
  83072. subIndex--;
  83073. }
  83074. if (currentPool.length < 2) {
  83075. continue;
  83076. }
  83077. // Merge meshes
  83078. BABYLON.Mesh.MergeMeshes(currentPool);
  83079. }
  83080. if (updateSelectionTree != undefined) {
  83081. if (updateSelectionTree) {
  83082. scene.createOrUpdateSelectionOctree();
  83083. }
  83084. }
  83085. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83086. scene.createOrUpdateSelectionOctree();
  83087. }
  83088. return true;
  83089. };
  83090. ;
  83091. MergeMeshesOptimization._UpdateSelectionTree = false;
  83092. return MergeMeshesOptimization;
  83093. }(SceneOptimization));
  83094. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83095. /**
  83096. * Defines a list of options used by SceneOptimizer
  83097. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83098. */
  83099. var SceneOptimizerOptions = /** @class */ (function () {
  83100. /**
  83101. * Creates a new list of options used by SceneOptimizer
  83102. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83103. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83104. */
  83105. function SceneOptimizerOptions(
  83106. /**
  83107. * Defines the target frame rate to reach (60 by default)
  83108. */
  83109. targetFrameRate,
  83110. /**
  83111. * Defines the interval between two checkes (2000ms by default)
  83112. */
  83113. trackerDuration) {
  83114. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83115. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83116. this.targetFrameRate = targetFrameRate;
  83117. this.trackerDuration = trackerDuration;
  83118. /**
  83119. * Gets the list of optimizations to apply
  83120. */
  83121. this.optimizations = new Array();
  83122. }
  83123. /**
  83124. * Add a new optimization
  83125. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83126. * @returns the current SceneOptimizerOptions
  83127. */
  83128. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83129. this.optimizations.push(optimization);
  83130. return this;
  83131. };
  83132. /**
  83133. * Add a new custom optimization
  83134. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83135. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83136. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83137. * @returns the current SceneOptimizerOptions
  83138. */
  83139. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83140. if (priority === void 0) { priority = 0; }
  83141. var optimization = new CustomOptimization(priority);
  83142. optimization.onApply = onApply;
  83143. optimization.onGetDescription = onGetDescription;
  83144. this.optimizations.push(optimization);
  83145. return this;
  83146. };
  83147. /**
  83148. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83149. * @param targetFrameRate defines the target frame rate (60 by default)
  83150. * @returns a SceneOptimizerOptions object
  83151. */
  83152. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83153. var result = new SceneOptimizerOptions(targetFrameRate);
  83154. var priority = 0;
  83155. result.addOptimization(new MergeMeshesOptimization(priority));
  83156. result.addOptimization(new ShadowsOptimization(priority));
  83157. result.addOptimization(new LensFlaresOptimization(priority));
  83158. // Next priority
  83159. priority++;
  83160. result.addOptimization(new PostProcessesOptimization(priority));
  83161. result.addOptimization(new ParticlesOptimization(priority));
  83162. // Next priority
  83163. priority++;
  83164. result.addOptimization(new TextureOptimization(priority, 1024));
  83165. return result;
  83166. };
  83167. /**
  83168. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83169. * @param targetFrameRate defines the target frame rate (60 by default)
  83170. * @returns a SceneOptimizerOptions object
  83171. */
  83172. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83173. var result = new SceneOptimizerOptions(targetFrameRate);
  83174. var priority = 0;
  83175. result.addOptimization(new MergeMeshesOptimization(priority));
  83176. result.addOptimization(new ShadowsOptimization(priority));
  83177. result.addOptimization(new LensFlaresOptimization(priority));
  83178. // Next priority
  83179. priority++;
  83180. result.addOptimization(new PostProcessesOptimization(priority));
  83181. result.addOptimization(new ParticlesOptimization(priority));
  83182. // Next priority
  83183. priority++;
  83184. result.addOptimization(new TextureOptimization(priority, 512));
  83185. // Next priority
  83186. priority++;
  83187. result.addOptimization(new RenderTargetsOptimization(priority));
  83188. // Next priority
  83189. priority++;
  83190. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83191. return result;
  83192. };
  83193. /**
  83194. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83195. * @param targetFrameRate defines the target frame rate (60 by default)
  83196. * @returns a SceneOptimizerOptions object
  83197. */
  83198. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83199. var result = new SceneOptimizerOptions(targetFrameRate);
  83200. var priority = 0;
  83201. result.addOptimization(new MergeMeshesOptimization(priority));
  83202. result.addOptimization(new ShadowsOptimization(priority));
  83203. result.addOptimization(new LensFlaresOptimization(priority));
  83204. // Next priority
  83205. priority++;
  83206. result.addOptimization(new PostProcessesOptimization(priority));
  83207. result.addOptimization(new ParticlesOptimization(priority));
  83208. // Next priority
  83209. priority++;
  83210. result.addOptimization(new TextureOptimization(priority, 256));
  83211. // Next priority
  83212. priority++;
  83213. result.addOptimization(new RenderTargetsOptimization(priority));
  83214. // Next priority
  83215. priority++;
  83216. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83217. return result;
  83218. };
  83219. return SceneOptimizerOptions;
  83220. }());
  83221. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83222. /**
  83223. * Class used to run optimizations in order to reach a target frame rate
  83224. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83225. */
  83226. var SceneOptimizer = /** @class */ (function () {
  83227. /**
  83228. * Creates a new SceneOptimizer
  83229. * @param scene defines the scene to work on
  83230. * @param options defines the options to use with the SceneOptimizer
  83231. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83232. * @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)
  83233. */
  83234. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83235. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83236. if (improvementMode === void 0) { improvementMode = false; }
  83237. var _this = this;
  83238. this._isRunning = false;
  83239. this._currentPriorityLevel = 0;
  83240. this._targetFrameRate = 60;
  83241. this._trackerDuration = 2000;
  83242. this._currentFrameRate = 0;
  83243. this._improvementMode = false;
  83244. /**
  83245. * Defines an observable called when the optimizer reaches the target frame rate
  83246. */
  83247. this.onSuccessObservable = new BABYLON.Observable();
  83248. /**
  83249. * Defines an observable called when the optimizer enables an optimization
  83250. */
  83251. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83252. /**
  83253. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83254. */
  83255. this.onFailureObservable = new BABYLON.Observable();
  83256. if (!options) {
  83257. this._options = new SceneOptimizerOptions();
  83258. }
  83259. else {
  83260. this._options = options;
  83261. }
  83262. if (this._options.targetFrameRate) {
  83263. this._targetFrameRate = this._options.targetFrameRate;
  83264. }
  83265. if (this._options.trackerDuration) {
  83266. this._trackerDuration = this._options.trackerDuration;
  83267. }
  83268. if (autoGeneratePriorities) {
  83269. var priority = 0;
  83270. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83271. var optim = _a[_i];
  83272. optim.priority = priority++;
  83273. }
  83274. }
  83275. this._improvementMode = improvementMode;
  83276. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83277. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83278. _this._sceneDisposeObserver = null;
  83279. _this.dispose();
  83280. });
  83281. }
  83282. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83283. /**
  83284. * Gets a boolean indicating if the optimizer is in improvement mode
  83285. */
  83286. get: function () {
  83287. return this._improvementMode;
  83288. },
  83289. enumerable: true,
  83290. configurable: true
  83291. });
  83292. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83293. /**
  83294. * Gets the current priority level (0 at start)
  83295. */
  83296. get: function () {
  83297. return this._currentPriorityLevel;
  83298. },
  83299. enumerable: true,
  83300. configurable: true
  83301. });
  83302. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83303. /**
  83304. * Gets the current frame rate checked by the SceneOptimizer
  83305. */
  83306. get: function () {
  83307. return this._currentFrameRate;
  83308. },
  83309. enumerable: true,
  83310. configurable: true
  83311. });
  83312. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83313. /**
  83314. * Gets or sets the current target frame rate (60 by default)
  83315. */
  83316. get: function () {
  83317. return this._targetFrameRate;
  83318. },
  83319. /**
  83320. * Gets or sets the current target frame rate (60 by default)
  83321. */
  83322. set: function (value) {
  83323. this._targetFrameRate = value;
  83324. },
  83325. enumerable: true,
  83326. configurable: true
  83327. });
  83328. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83329. /**
  83330. * Gets or sets the current interval between two checks (every 2000ms by default)
  83331. */
  83332. get: function () {
  83333. return this._trackerDuration;
  83334. },
  83335. /**
  83336. * Gets or sets the current interval between two checks (every 2000ms by default)
  83337. */
  83338. set: function (value) {
  83339. this._trackerDuration = value;
  83340. },
  83341. enumerable: true,
  83342. configurable: true
  83343. });
  83344. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83345. /**
  83346. * Gets the list of active optimizations
  83347. */
  83348. get: function () {
  83349. return this._options.optimizations;
  83350. },
  83351. enumerable: true,
  83352. configurable: true
  83353. });
  83354. /**
  83355. * Stops the current optimizer
  83356. */
  83357. SceneOptimizer.prototype.stop = function () {
  83358. this._isRunning = false;
  83359. };
  83360. /**
  83361. * Reset the optimizer to initial step (current priority level = 0)
  83362. */
  83363. SceneOptimizer.prototype.reset = function () {
  83364. this._currentPriorityLevel = 0;
  83365. };
  83366. /**
  83367. * Start the optimizer. By default it will try to reach a specific framerate
  83368. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83369. */
  83370. SceneOptimizer.prototype.start = function () {
  83371. var _this = this;
  83372. if (this._isRunning) {
  83373. return;
  83374. }
  83375. this._isRunning = true;
  83376. // Let's wait for the scene to be ready before running our check
  83377. this._scene.executeWhenReady(function () {
  83378. setTimeout(function () {
  83379. _this._checkCurrentState();
  83380. }, _this._trackerDuration);
  83381. });
  83382. };
  83383. SceneOptimizer.prototype._checkCurrentState = function () {
  83384. var _this = this;
  83385. if (!this._isRunning) {
  83386. return;
  83387. }
  83388. var scene = this._scene;
  83389. var options = this._options;
  83390. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83391. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83392. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83393. this._isRunning = false;
  83394. this.onSuccessObservable.notifyObservers(this);
  83395. return;
  83396. }
  83397. // Apply current level of optimizations
  83398. var allDone = true;
  83399. var noOptimizationApplied = true;
  83400. for (var index = 0; index < options.optimizations.length; index++) {
  83401. var optimization = options.optimizations[index];
  83402. if (optimization.priority === this._currentPriorityLevel) {
  83403. noOptimizationApplied = false;
  83404. allDone = allDone && optimization.apply(scene, this);
  83405. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83406. }
  83407. }
  83408. // If no optimization was applied, this is a failure :(
  83409. if (noOptimizationApplied) {
  83410. this._isRunning = false;
  83411. this.onFailureObservable.notifyObservers(this);
  83412. return;
  83413. }
  83414. // If all optimizations were done, move to next level
  83415. if (allDone) {
  83416. this._currentPriorityLevel++;
  83417. }
  83418. // Let's the system running for a specific amount of time before checking FPS
  83419. scene.executeWhenReady(function () {
  83420. setTimeout(function () {
  83421. _this._checkCurrentState();
  83422. }, _this._trackerDuration);
  83423. });
  83424. };
  83425. /**
  83426. * Release all resources
  83427. */
  83428. SceneOptimizer.prototype.dispose = function () {
  83429. this.stop();
  83430. this.onSuccessObservable.clear();
  83431. this.onFailureObservable.clear();
  83432. this.onNewOptimizationAppliedObservable.clear();
  83433. if (this._sceneDisposeObserver) {
  83434. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83435. }
  83436. };
  83437. /**
  83438. * Helper function to create a SceneOptimizer with one single line of code
  83439. * @param scene defines the scene to work on
  83440. * @param options defines the options to use with the SceneOptimizer
  83441. * @param onSuccess defines a callback to call on success
  83442. * @param onFailure defines a callback to call on failure
  83443. * @returns the new SceneOptimizer object
  83444. */
  83445. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83446. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83447. if (onSuccess) {
  83448. optimizer.onSuccessObservable.add(function () {
  83449. onSuccess();
  83450. });
  83451. }
  83452. if (onFailure) {
  83453. optimizer.onFailureObservable.add(function () {
  83454. onFailure();
  83455. });
  83456. }
  83457. optimizer.start();
  83458. return optimizer;
  83459. };
  83460. return SceneOptimizer;
  83461. }());
  83462. BABYLON.SceneOptimizer = SceneOptimizer;
  83463. })(BABYLON || (BABYLON = {}));
  83464. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83465. var BABYLON;
  83466. (function (BABYLON) {
  83467. var OutlineRenderer = /** @class */ (function () {
  83468. function OutlineRenderer(scene) {
  83469. this.zOffset = 1;
  83470. this._scene = scene;
  83471. }
  83472. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83473. var _this = this;
  83474. if (useOverlay === void 0) { useOverlay = false; }
  83475. var scene = this._scene;
  83476. var engine = this._scene.getEngine();
  83477. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83478. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83479. return;
  83480. }
  83481. var mesh = subMesh.getRenderingMesh();
  83482. var material = subMesh.getMaterial();
  83483. if (!material || !scene.activeCamera) {
  83484. return;
  83485. }
  83486. engine.enableEffect(this._effect);
  83487. // Logarithmic depth
  83488. if (material.useLogarithmicDepth) {
  83489. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83490. }
  83491. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83492. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83493. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83494. // Bones
  83495. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83496. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83497. }
  83498. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83499. // Alpha test
  83500. if (material && material.needAlphaTesting()) {
  83501. var alphaTexture = material.getAlphaTestTexture();
  83502. if (alphaTexture) {
  83503. this._effect.setTexture("diffuseSampler", alphaTexture);
  83504. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83505. }
  83506. }
  83507. engine.setZOffset(-this.zOffset);
  83508. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83509. engine.setZOffset(0);
  83510. };
  83511. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83512. var defines = [];
  83513. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83514. var mesh = subMesh.getMesh();
  83515. var material = subMesh.getMaterial();
  83516. if (material) {
  83517. // Alpha test
  83518. if (material.needAlphaTesting()) {
  83519. defines.push("#define ALPHATEST");
  83520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83521. attribs.push(BABYLON.VertexBuffer.UVKind);
  83522. defines.push("#define UV1");
  83523. }
  83524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83525. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83526. defines.push("#define UV2");
  83527. }
  83528. }
  83529. //Logarithmic depth
  83530. if (material.useLogarithmicDepth) {
  83531. defines.push("#define LOGARITHMICDEPTH");
  83532. }
  83533. }
  83534. // Bones
  83535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83538. if (mesh.numBoneInfluencers > 4) {
  83539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83541. }
  83542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83543. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83544. }
  83545. else {
  83546. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83547. }
  83548. // Instances
  83549. if (useInstances) {
  83550. defines.push("#define INSTANCES");
  83551. attribs.push("world0");
  83552. attribs.push("world1");
  83553. attribs.push("world2");
  83554. attribs.push("world3");
  83555. }
  83556. // Get correct effect
  83557. var join = defines.join("\n");
  83558. if (this._cachedDefines !== join) {
  83559. this._cachedDefines = join;
  83560. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83561. }
  83562. return this._effect.isReady();
  83563. };
  83564. return OutlineRenderer;
  83565. }());
  83566. BABYLON.OutlineRenderer = OutlineRenderer;
  83567. })(BABYLON || (BABYLON = {}));
  83568. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83569. var BABYLON;
  83570. (function (BABYLON) {
  83571. var FaceAdjacencies = /** @class */ (function () {
  83572. function FaceAdjacencies() {
  83573. this.edges = new Array();
  83574. this.edgesConnectedCount = 0;
  83575. }
  83576. return FaceAdjacencies;
  83577. }());
  83578. var EdgesRenderer = /** @class */ (function () {
  83579. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83580. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83581. if (epsilon === void 0) { epsilon = 0.95; }
  83582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83583. this.edgesWidthScalerForOrthographic = 1000.0;
  83584. this.edgesWidthScalerForPerspective = 50.0;
  83585. this._linesPositions = new Array();
  83586. this._linesNormals = new Array();
  83587. this._linesIndices = new Array();
  83588. this._buffers = {};
  83589. this._checkVerticesInsteadOfIndices = false;
  83590. this._source = source;
  83591. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83592. this._epsilon = epsilon;
  83593. this._prepareRessources();
  83594. this._generateEdgesLines();
  83595. }
  83596. EdgesRenderer.prototype._prepareRessources = function () {
  83597. if (this._lineShader) {
  83598. return;
  83599. }
  83600. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83601. attributes: ["position", "normal"],
  83602. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83603. });
  83604. this._lineShader.disableDepthWrite = true;
  83605. this._lineShader.backFaceCulling = false;
  83606. };
  83607. EdgesRenderer.prototype._rebuild = function () {
  83608. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83609. if (buffer) {
  83610. buffer._rebuild();
  83611. }
  83612. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83613. if (buffer) {
  83614. buffer._rebuild();
  83615. }
  83616. var scene = this._source.getScene();
  83617. var engine = scene.getEngine();
  83618. this._ib = engine.createIndexBuffer(this._linesIndices);
  83619. };
  83620. EdgesRenderer.prototype.dispose = function () {
  83621. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83622. if (buffer) {
  83623. buffer.dispose();
  83624. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83625. }
  83626. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83627. if (buffer) {
  83628. buffer.dispose();
  83629. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83630. }
  83631. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83632. this._lineShader.dispose();
  83633. };
  83634. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83635. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83636. return 0;
  83637. }
  83638. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83639. return 1;
  83640. }
  83641. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83642. return 2;
  83643. }
  83644. return -1;
  83645. };
  83646. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83647. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83648. return 0;
  83649. }
  83650. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83651. return 1;
  83652. }
  83653. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83654. return 2;
  83655. }
  83656. return -1;
  83657. };
  83658. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83659. var needToCreateLine;
  83660. if (edge === undefined) {
  83661. needToCreateLine = true;
  83662. }
  83663. else {
  83664. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83665. needToCreateLine = dotProduct < this._epsilon;
  83666. }
  83667. if (needToCreateLine) {
  83668. var offset = this._linesPositions.length / 3;
  83669. var normal = p0.subtract(p1);
  83670. normal.normalize();
  83671. // Positions
  83672. this._linesPositions.push(p0.x);
  83673. this._linesPositions.push(p0.y);
  83674. this._linesPositions.push(p0.z);
  83675. this._linesPositions.push(p0.x);
  83676. this._linesPositions.push(p0.y);
  83677. this._linesPositions.push(p0.z);
  83678. this._linesPositions.push(p1.x);
  83679. this._linesPositions.push(p1.y);
  83680. this._linesPositions.push(p1.z);
  83681. this._linesPositions.push(p1.x);
  83682. this._linesPositions.push(p1.y);
  83683. this._linesPositions.push(p1.z);
  83684. // Normals
  83685. this._linesNormals.push(p1.x);
  83686. this._linesNormals.push(p1.y);
  83687. this._linesNormals.push(p1.z);
  83688. this._linesNormals.push(-1);
  83689. this._linesNormals.push(p1.x);
  83690. this._linesNormals.push(p1.y);
  83691. this._linesNormals.push(p1.z);
  83692. this._linesNormals.push(1);
  83693. this._linesNormals.push(p0.x);
  83694. this._linesNormals.push(p0.y);
  83695. this._linesNormals.push(p0.z);
  83696. this._linesNormals.push(-1);
  83697. this._linesNormals.push(p0.x);
  83698. this._linesNormals.push(p0.y);
  83699. this._linesNormals.push(p0.z);
  83700. this._linesNormals.push(1);
  83701. // Indices
  83702. this._linesIndices.push(offset);
  83703. this._linesIndices.push(offset + 1);
  83704. this._linesIndices.push(offset + 2);
  83705. this._linesIndices.push(offset);
  83706. this._linesIndices.push(offset + 2);
  83707. this._linesIndices.push(offset + 3);
  83708. }
  83709. };
  83710. EdgesRenderer.prototype._generateEdgesLines = function () {
  83711. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83712. var indices = this._source.getIndices();
  83713. if (!indices || !positions) {
  83714. return;
  83715. }
  83716. // First let's find adjacencies
  83717. var adjacencies = new Array();
  83718. var faceNormals = new Array();
  83719. var index;
  83720. var faceAdjacencies;
  83721. // Prepare faces
  83722. for (index = 0; index < indices.length; index += 3) {
  83723. faceAdjacencies = new FaceAdjacencies();
  83724. var p0Index = indices[index];
  83725. var p1Index = indices[index + 1];
  83726. var p2Index = indices[index + 2];
  83727. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83728. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83729. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83730. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83731. faceNormal.normalize();
  83732. faceNormals.push(faceNormal);
  83733. adjacencies.push(faceAdjacencies);
  83734. }
  83735. // Scan
  83736. for (index = 0; index < adjacencies.length; index++) {
  83737. faceAdjacencies = adjacencies[index];
  83738. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83739. var otherFaceAdjacencies = adjacencies[otherIndex];
  83740. if (faceAdjacencies.edgesConnectedCount === 3) {
  83741. break;
  83742. }
  83743. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83744. continue;
  83745. }
  83746. var otherP0 = indices[otherIndex * 3];
  83747. var otherP1 = indices[otherIndex * 3 + 1];
  83748. var otherP2 = indices[otherIndex * 3 + 2];
  83749. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83750. var otherEdgeIndex = 0;
  83751. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83752. continue;
  83753. }
  83754. switch (edgeIndex) {
  83755. case 0:
  83756. if (this._checkVerticesInsteadOfIndices) {
  83757. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83758. }
  83759. else {
  83760. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83761. }
  83762. break;
  83763. case 1:
  83764. if (this._checkVerticesInsteadOfIndices) {
  83765. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83766. }
  83767. else {
  83768. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83769. }
  83770. break;
  83771. case 2:
  83772. if (this._checkVerticesInsteadOfIndices) {
  83773. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83774. }
  83775. else {
  83776. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83777. }
  83778. break;
  83779. }
  83780. if (otherEdgeIndex === -1) {
  83781. continue;
  83782. }
  83783. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83784. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83785. faceAdjacencies.edgesConnectedCount++;
  83786. otherFaceAdjacencies.edgesConnectedCount++;
  83787. if (faceAdjacencies.edgesConnectedCount === 3) {
  83788. break;
  83789. }
  83790. }
  83791. }
  83792. }
  83793. // Create lines
  83794. for (index = 0; index < adjacencies.length; index++) {
  83795. // 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
  83796. var current = adjacencies[index];
  83797. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83798. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83799. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83800. }
  83801. // Merge into a single mesh
  83802. var engine = this._source.getScene().getEngine();
  83803. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83804. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83805. this._ib = engine.createIndexBuffer(this._linesIndices);
  83806. this._indicesCount = this._linesIndices.length;
  83807. };
  83808. EdgesRenderer.prototype.render = function () {
  83809. var scene = this._source.getScene();
  83810. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83811. return;
  83812. }
  83813. var engine = scene.getEngine();
  83814. this._lineShader._preBind();
  83815. // VBOs
  83816. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83817. scene.resetCachedMaterial();
  83818. this._lineShader.setColor4("color", this._source.edgesColor);
  83819. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83820. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83821. }
  83822. else {
  83823. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83824. }
  83825. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83826. this._lineShader.bind(this._source.getWorldMatrix());
  83827. // Draw order
  83828. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83829. this._lineShader.unbind();
  83830. engine.setDepthWrite(true);
  83831. };
  83832. return EdgesRenderer;
  83833. }());
  83834. BABYLON.EdgesRenderer = EdgesRenderer;
  83835. })(BABYLON || (BABYLON = {}));
  83836. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83837. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83838. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83839. s = arguments[i];
  83840. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83841. t[p] = s[p];
  83842. }
  83843. return t;
  83844. };
  83845. var BABYLON;
  83846. (function (BABYLON) {
  83847. /**
  83848. * The effect layer Helps adding post process effect blended with the main pass.
  83849. *
  83850. * This can be for instance use to generate glow or higlight effects on the scene.
  83851. *
  83852. * The effect layer class can not be used directly and is intented to inherited from to be
  83853. * customized per effects.
  83854. */
  83855. var EffectLayer = /** @class */ (function () {
  83856. /**
  83857. * Instantiates a new effect Layer and references it in the scene.
  83858. * @param name The name of the layer
  83859. * @param scene The scene to use the layer in
  83860. */
  83861. function EffectLayer(
  83862. /** The Friendly of the effect in the scene */
  83863. name, scene) {
  83864. this.name = name;
  83865. this._vertexBuffers = {};
  83866. this._maxSize = 0;
  83867. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83868. this._shouldRender = true;
  83869. this._postProcesses = [];
  83870. this._textures = [];
  83871. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83872. /**
  83873. * The clear color of the texture used to generate the glow map.
  83874. */
  83875. this.neutralColor = new BABYLON.Color4();
  83876. /**
  83877. * Specifies wether the highlight layer is enabled or not.
  83878. */
  83879. this.isEnabled = true;
  83880. /**
  83881. * An event triggered when the effect layer has been disposed.
  83882. */
  83883. this.onDisposeObservable = new BABYLON.Observable();
  83884. /**
  83885. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83886. */
  83887. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83888. /**
  83889. * An event triggered when the generated texture is being merged in the scene.
  83890. */
  83891. this.onBeforeComposeObservable = new BABYLON.Observable();
  83892. /**
  83893. * An event triggered when the generated texture has been merged in the scene.
  83894. */
  83895. this.onAfterComposeObservable = new BABYLON.Observable();
  83896. /**
  83897. * An event triggered when the efffect layer changes its size.
  83898. */
  83899. this.onSizeChangedObservable = new BABYLON.Observable();
  83900. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83901. this._engine = scene.getEngine();
  83902. this._maxSize = this._engine.getCaps().maxTextureSize;
  83903. this._scene.effectLayers.push(this);
  83904. // Generate Buffers
  83905. this._generateIndexBuffer();
  83906. this._genrateVertexBuffer();
  83907. }
  83908. Object.defineProperty(EffectLayer.prototype, "camera", {
  83909. /**
  83910. * Gets the camera attached to the layer.
  83911. */
  83912. get: function () {
  83913. return this._effectLayerOptions.camera;
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. /**
  83919. * Initializes the effect layer with the required options.
  83920. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83921. */
  83922. EffectLayer.prototype._init = function (options) {
  83923. // Adapt options
  83924. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83925. this._setMainTextureSize();
  83926. this._createMainTexture();
  83927. this._createTextureAndPostProcesses();
  83928. this._mergeEffect = this._createMergeEffect();
  83929. };
  83930. /**
  83931. * Generates the index buffer of the full screen quad blending to the main canvas.
  83932. */
  83933. EffectLayer.prototype._generateIndexBuffer = function () {
  83934. // Indices
  83935. var indices = [];
  83936. indices.push(0);
  83937. indices.push(1);
  83938. indices.push(2);
  83939. indices.push(0);
  83940. indices.push(2);
  83941. indices.push(3);
  83942. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83943. };
  83944. /**
  83945. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83946. */
  83947. EffectLayer.prototype._genrateVertexBuffer = function () {
  83948. // VBO
  83949. var vertices = [];
  83950. vertices.push(1, 1);
  83951. vertices.push(-1, 1);
  83952. vertices.push(-1, -1);
  83953. vertices.push(1, -1);
  83954. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83956. };
  83957. /**
  83958. * Sets the main texture desired size which is the closest power of two
  83959. * of the engine canvas size.
  83960. */
  83961. EffectLayer.prototype._setMainTextureSize = function () {
  83962. if (this._effectLayerOptions.mainTextureFixedSize) {
  83963. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83964. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83965. }
  83966. else {
  83967. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83968. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83969. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83970. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83971. }
  83972. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83973. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83974. };
  83975. /**
  83976. * Creates the main texture for the effect layer.
  83977. */
  83978. EffectLayer.prototype._createMainTexture = function () {
  83979. var _this = this;
  83980. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83981. width: this._mainTextureDesiredSize.width,
  83982. height: this._mainTextureDesiredSize.height
  83983. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83984. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83985. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83986. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83987. this._mainTexture.anisotropicFilteringLevel = 1;
  83988. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83989. this._mainTexture.renderParticles = false;
  83990. this._mainTexture.renderList = null;
  83991. this._mainTexture.ignoreCameraViewport = true;
  83992. // Custom render function
  83993. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83994. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83995. var index;
  83996. var engine = _this._scene.getEngine();
  83997. if (depthOnlySubMeshes.length) {
  83998. engine.setColorWrite(false);
  83999. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84000. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84001. }
  84002. engine.setColorWrite(true);
  84003. }
  84004. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84005. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84006. }
  84007. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84008. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84009. }
  84010. for (index = 0; index < transparentSubMeshes.length; index++) {
  84011. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84012. }
  84013. };
  84014. this._mainTexture.onClearObservable.add(function (engine) {
  84015. engine.clear(_this.neutralColor, true, true, true);
  84016. });
  84017. };
  84018. /**
  84019. * Checks for the readiness of the element composing the layer.
  84020. * @param subMesh the mesh to check for
  84021. * @param useInstances specify wether or not to use instances to render the mesh
  84022. * @param emissiveTexture the associated emissive texture used to generate the glow
  84023. * @return true if ready otherwise, false
  84024. */
  84025. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84026. var material = subMesh.getMaterial();
  84027. if (!material) {
  84028. return false;
  84029. }
  84030. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84031. return false;
  84032. }
  84033. var defines = [];
  84034. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84035. var mesh = subMesh.getMesh();
  84036. var uv1 = false;
  84037. var uv2 = false;
  84038. // Alpha test
  84039. if (material && material.needAlphaTesting()) {
  84040. var alphaTexture = material.getAlphaTestTexture();
  84041. if (alphaTexture) {
  84042. defines.push("#define ALPHATEST");
  84043. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84044. alphaTexture.coordinatesIndex === 1) {
  84045. defines.push("#define DIFFUSEUV2");
  84046. uv2 = true;
  84047. }
  84048. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84049. defines.push("#define DIFFUSEUV1");
  84050. uv1 = true;
  84051. }
  84052. }
  84053. }
  84054. // Emissive
  84055. if (emissiveTexture) {
  84056. defines.push("#define EMISSIVE");
  84057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84058. emissiveTexture.coordinatesIndex === 1) {
  84059. defines.push("#define EMISSIVEUV2");
  84060. uv2 = true;
  84061. }
  84062. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84063. defines.push("#define EMISSIVEUV1");
  84064. uv1 = true;
  84065. }
  84066. }
  84067. if (uv1) {
  84068. attribs.push(BABYLON.VertexBuffer.UVKind);
  84069. defines.push("#define UV1");
  84070. }
  84071. if (uv2) {
  84072. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84073. defines.push("#define UV2");
  84074. }
  84075. // Bones
  84076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84079. if (mesh.numBoneInfluencers > 4) {
  84080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84082. }
  84083. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84084. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84085. }
  84086. else {
  84087. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84088. }
  84089. // Instances
  84090. if (useInstances) {
  84091. defines.push("#define INSTANCES");
  84092. attribs.push("world0");
  84093. attribs.push("world1");
  84094. attribs.push("world2");
  84095. attribs.push("world3");
  84096. }
  84097. // Get correct effect
  84098. var join = defines.join("\n");
  84099. if (this._cachedDefines !== join) {
  84100. this._cachedDefines = join;
  84101. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84102. }
  84103. return this._effectLayerMapGenerationEffect.isReady();
  84104. };
  84105. /**
  84106. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84107. */
  84108. EffectLayer.prototype.render = function () {
  84109. var currentEffect = this._mergeEffect;
  84110. // Check
  84111. if (!currentEffect.isReady())
  84112. return;
  84113. for (var i = 0; i < this._postProcesses.length; i++) {
  84114. if (!this._postProcesses[i].isReady()) {
  84115. return;
  84116. }
  84117. }
  84118. var engine = this._scene.getEngine();
  84119. this.onBeforeComposeObservable.notifyObservers(this);
  84120. // Render
  84121. engine.enableEffect(currentEffect);
  84122. engine.setState(false);
  84123. // VBOs
  84124. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84125. // Cache
  84126. var previousAlphaMode = engine.getAlphaMode();
  84127. // Go Blend.
  84128. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84129. // Blends the map on the main canvas.
  84130. this._internalRender(currentEffect);
  84131. // Restore Alpha
  84132. engine.setAlphaMode(previousAlphaMode);
  84133. this.onAfterComposeObservable.notifyObservers(this);
  84134. // Handle size changes.
  84135. var size = this._mainTexture.getSize();
  84136. this._setMainTextureSize();
  84137. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84138. // Recreate RTT and post processes on size change.
  84139. this.onSizeChangedObservable.notifyObservers(this);
  84140. this._disposeTextureAndPostProcesses();
  84141. this._createMainTexture();
  84142. this._createTextureAndPostProcesses();
  84143. }
  84144. };
  84145. /**
  84146. * Determine if a given mesh will be used in the current effect.
  84147. * @param mesh mesh to test
  84148. * @returns true if the mesh will be used
  84149. */
  84150. EffectLayer.prototype.hasMesh = function (mesh) {
  84151. return true;
  84152. };
  84153. /**
  84154. * Returns true if the layer contains information to display, otherwise false.
  84155. * @returns true if the glow layer should be rendered
  84156. */
  84157. EffectLayer.prototype.shouldRender = function () {
  84158. return this.isEnabled && this._shouldRender;
  84159. };
  84160. /**
  84161. * Returns true if the mesh should render, otherwise false.
  84162. * @param mesh The mesh to render
  84163. * @returns true if it should render otherwise false
  84164. */
  84165. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84166. return true;
  84167. };
  84168. /**
  84169. * Returns true if the mesh should render, otherwise false.
  84170. * @param mesh The mesh to render
  84171. * @returns true if it should render otherwise false
  84172. */
  84173. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84174. return true;
  84175. };
  84176. /**
  84177. * Renders the submesh passed in parameter to the generation map.
  84178. */
  84179. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84180. var _this = this;
  84181. if (!this.shouldRender()) {
  84182. return;
  84183. }
  84184. var material = subMesh.getMaterial();
  84185. var mesh = subMesh.getRenderingMesh();
  84186. var scene = this._scene;
  84187. var engine = scene.getEngine();
  84188. if (!material) {
  84189. return;
  84190. }
  84191. // Do not block in blend mode.
  84192. if (material.needAlphaBlendingForMesh(mesh)) {
  84193. return;
  84194. }
  84195. // Culling
  84196. engine.setState(material.backFaceCulling);
  84197. // Managing instances
  84198. var batch = mesh._getInstancesRenderList(subMesh._id);
  84199. if (batch.mustReturn) {
  84200. return;
  84201. }
  84202. // Early Exit per mesh
  84203. if (!this._shouldRenderMesh(mesh)) {
  84204. return;
  84205. }
  84206. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84207. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84208. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84209. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84210. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84211. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84212. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84213. // Alpha test
  84214. if (material && material.needAlphaTesting()) {
  84215. var alphaTexture = material.getAlphaTestTexture();
  84216. if (alphaTexture) {
  84217. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84218. var textureMatrix = alphaTexture.getTextureMatrix();
  84219. if (textureMatrix) {
  84220. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84221. }
  84222. }
  84223. }
  84224. // Glow emissive only
  84225. if (this._emissiveTextureAndColor.texture) {
  84226. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84227. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84228. }
  84229. // Bones
  84230. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84231. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84232. }
  84233. // Draw
  84234. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84235. }
  84236. else {
  84237. // Need to reset refresh rate of the shadowMap
  84238. this._mainTexture.resetRefreshCounter();
  84239. }
  84240. };
  84241. /**
  84242. * Rebuild the required buffers.
  84243. * @ignore Internal use only.
  84244. */
  84245. EffectLayer.prototype._rebuild = function () {
  84246. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84247. if (vb) {
  84248. vb._rebuild();
  84249. }
  84250. this._generateIndexBuffer();
  84251. };
  84252. /**
  84253. * Dispose only the render target textures and post process.
  84254. */
  84255. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84256. this._mainTexture.dispose();
  84257. for (var i = 0; i < this._postProcesses.length; i++) {
  84258. if (this._postProcesses[i]) {
  84259. this._postProcesses[i].dispose();
  84260. }
  84261. }
  84262. this._postProcesses = [];
  84263. for (var i = 0; i < this._textures.length; i++) {
  84264. if (this._textures[i]) {
  84265. this._textures[i].dispose();
  84266. }
  84267. }
  84268. this._textures = [];
  84269. };
  84270. /**
  84271. * Dispose the highlight layer and free resources.
  84272. */
  84273. EffectLayer.prototype.dispose = function () {
  84274. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84275. if (vertexBuffer) {
  84276. vertexBuffer.dispose();
  84277. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84278. }
  84279. if (this._indexBuffer) {
  84280. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84281. this._indexBuffer = null;
  84282. }
  84283. // Clean textures and post processes
  84284. this._disposeTextureAndPostProcesses();
  84285. // Remove from scene
  84286. var index = this._scene.effectLayers.indexOf(this, 0);
  84287. if (index > -1) {
  84288. this._scene.effectLayers.splice(index, 1);
  84289. }
  84290. // Callback
  84291. this.onDisposeObservable.notifyObservers(this);
  84292. this.onDisposeObservable.clear();
  84293. this.onBeforeRenderMainTextureObservable.clear();
  84294. this.onBeforeComposeObservable.clear();
  84295. this.onAfterComposeObservable.clear();
  84296. this.onSizeChangedObservable.clear();
  84297. };
  84298. return EffectLayer;
  84299. }());
  84300. BABYLON.EffectLayer = EffectLayer;
  84301. })(BABYLON || (BABYLON = {}));
  84302. //# sourceMappingURL=babylon.effectLayer.js.map
  84303. var BABYLON;
  84304. (function (BABYLON) {
  84305. /**
  84306. * Special Glow Blur post process only blurring the alpha channel
  84307. * It enforces keeping the most luminous color in the color channel.
  84308. */
  84309. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84310. __extends(GlowBlurPostProcess, _super);
  84311. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84313. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84314. _this.direction = direction;
  84315. _this.kernel = kernel;
  84316. _this.onApplyObservable.add(function (effect) {
  84317. effect.setFloat2("screenSize", _this.width, _this.height);
  84318. effect.setVector2("direction", _this.direction);
  84319. effect.setFloat("blurWidth", _this.kernel);
  84320. });
  84321. return _this;
  84322. }
  84323. return GlowBlurPostProcess;
  84324. }(BABYLON.PostProcess));
  84325. /**
  84326. * The highlight layer Helps adding a glow effect around a mesh.
  84327. *
  84328. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84329. * glowy meshes to your scene.
  84330. *
  84331. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84332. */
  84333. var HighlightLayer = /** @class */ (function (_super) {
  84334. __extends(HighlightLayer, _super);
  84335. /**
  84336. * Instantiates a new highlight Layer and references it to the scene..
  84337. * @param name The name of the layer
  84338. * @param scene The scene to use the layer in
  84339. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84340. */
  84341. function HighlightLayer(name, scene, options) {
  84342. var _this = _super.call(this, name, scene) || this;
  84343. _this.name = name;
  84344. /**
  84345. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84346. */
  84347. _this.innerGlow = true;
  84348. /**
  84349. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84350. */
  84351. _this.outerGlow = true;
  84352. /**
  84353. * An event triggered when the highlight layer is being blurred.
  84354. */
  84355. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84356. /**
  84357. * An event triggered when the highlight layer has been blurred.
  84358. */
  84359. _this.onAfterBlurObservable = new BABYLON.Observable();
  84360. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84361. _this._meshes = {};
  84362. _this._excludedMeshes = {};
  84363. _this.neutralColor = HighlightLayer.NeutralColor;
  84364. // Warn on stencil
  84365. if (!_this._engine.isStencilEnable) {
  84366. 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 }");
  84367. }
  84368. // Adapt options
  84369. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84370. // Initialize the layer
  84371. _this._init({
  84372. alphaBlendingMode: _this._options.alphaBlendingMode,
  84373. camera: _this._options.camera,
  84374. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84375. mainTextureRatio: _this._options.mainTextureRatio
  84376. });
  84377. // Do not render as long as no meshes have been added
  84378. _this._shouldRender = false;
  84379. return _this;
  84380. }
  84381. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84382. /**
  84383. * Gets the horizontal size of the blur.
  84384. */
  84385. get: function () {
  84386. return this._horizontalBlurPostprocess.kernel;
  84387. },
  84388. /**
  84389. * Specifies the horizontal size of the blur.
  84390. */
  84391. set: function (value) {
  84392. this._horizontalBlurPostprocess.kernel = value;
  84393. },
  84394. enumerable: true,
  84395. configurable: true
  84396. });
  84397. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84398. /**
  84399. * Gets the vertical size of the blur.
  84400. */
  84401. get: function () {
  84402. return this._verticalBlurPostprocess.kernel;
  84403. },
  84404. /**
  84405. * Specifies the vertical size of the blur.
  84406. */
  84407. set: function (value) {
  84408. this._verticalBlurPostprocess.kernel = value;
  84409. },
  84410. enumerable: true,
  84411. configurable: true
  84412. });
  84413. /**
  84414. * Get the effect name of the layer.
  84415. * @return The effect name
  84416. */
  84417. HighlightLayer.prototype.getEffectName = function () {
  84418. return HighlightLayer.EffectName;
  84419. };
  84420. /**
  84421. * Create the merge effect. This is the shader use to blit the information back
  84422. * to the main canvas at the end of the scene rendering.
  84423. */
  84424. HighlightLayer.prototype._createMergeEffect = function () {
  84425. // Effect
  84426. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84427. };
  84428. /**
  84429. * Creates the render target textures and post processes used in the highlight layer.
  84430. */
  84431. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84432. var _this = this;
  84433. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84434. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84435. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84436. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84437. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84438. width: blurTextureWidth,
  84439. height: blurTextureHeight
  84440. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84441. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84442. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84443. this._blurTexture.anisotropicFilteringLevel = 16;
  84444. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84445. this._blurTexture.renderParticles = false;
  84446. this._blurTexture.ignoreCameraViewport = true;
  84447. this._textures = [this._blurTexture];
  84448. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84449. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84450. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84451. effect.setTexture("textureSampler", _this._mainTexture);
  84452. });
  84453. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84454. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84455. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84456. });
  84457. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84458. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84459. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84460. });
  84461. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84462. }
  84463. else {
  84464. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84465. width: blurTextureWidth,
  84466. height: blurTextureHeight
  84467. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84468. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84469. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84470. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84471. effect.setTexture("textureSampler", _this._mainTexture);
  84472. });
  84473. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84474. width: blurTextureWidth,
  84475. height: blurTextureHeight
  84476. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84477. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84478. }
  84479. this._mainTexture.onAfterUnbindObservable.add(function () {
  84480. _this.onBeforeBlurObservable.notifyObservers(_this);
  84481. var internalTexture = _this._blurTexture.getInternalTexture();
  84482. if (internalTexture) {
  84483. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84484. }
  84485. _this.onAfterBlurObservable.notifyObservers(_this);
  84486. });
  84487. // Prevent autoClear.
  84488. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84489. };
  84490. /**
  84491. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84492. */
  84493. HighlightLayer.prototype.needStencil = function () {
  84494. return true;
  84495. };
  84496. /**
  84497. * Checks for the readiness of the element composing the layer.
  84498. * @param subMesh the mesh to check for
  84499. * @param useInstances specify wether or not to use instances to render the mesh
  84500. * @param emissiveTexture the associated emissive texture used to generate the glow
  84501. * @return true if ready otherwise, false
  84502. */
  84503. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84504. var material = subMesh.getMaterial();
  84505. var mesh = subMesh.getRenderingMesh();
  84506. if (!material || !mesh || !this._meshes) {
  84507. return false;
  84508. }
  84509. var emissiveTexture = null;
  84510. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84511. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84512. emissiveTexture = material.emissiveTexture;
  84513. }
  84514. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84515. };
  84516. /**
  84517. * Implementation specific of rendering the generating effect on the main canvas.
  84518. * @param effect The effect used to render through
  84519. */
  84520. HighlightLayer.prototype._internalRender = function (effect) {
  84521. // Texture
  84522. effect.setTexture("textureSampler", this._blurTexture);
  84523. // Cache
  84524. var engine = this._engine;
  84525. var previousStencilBuffer = engine.getStencilBuffer();
  84526. var previousStencilFunction = engine.getStencilFunction();
  84527. var previousStencilMask = engine.getStencilMask();
  84528. var previousStencilOperationPass = engine.getStencilOperationPass();
  84529. var previousStencilOperationFail = engine.getStencilOperationFail();
  84530. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84531. var previousStencilReference = engine.getStencilFunctionReference();
  84532. // Stencil operations
  84533. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84534. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84535. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84536. // Draw order
  84537. engine.setStencilMask(0x00);
  84538. engine.setStencilBuffer(true);
  84539. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84540. // 2 passes inner outer
  84541. if (this.outerGlow) {
  84542. effect.setFloat("offset", 0);
  84543. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84545. }
  84546. if (this.innerGlow) {
  84547. effect.setFloat("offset", 1);
  84548. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84549. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84550. }
  84551. // Restore Cache
  84552. engine.setStencilFunction(previousStencilFunction);
  84553. engine.setStencilMask(previousStencilMask);
  84554. engine.setStencilBuffer(previousStencilBuffer);
  84555. engine.setStencilOperationPass(previousStencilOperationPass);
  84556. engine.setStencilOperationFail(previousStencilOperationFail);
  84557. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84558. engine.setStencilFunctionReference(previousStencilReference);
  84559. };
  84560. /**
  84561. * Returns true if the layer contains information to display, otherwise false.
  84562. */
  84563. HighlightLayer.prototype.shouldRender = function () {
  84564. if (_super.prototype.shouldRender.call(this)) {
  84565. return this._meshes ? true : false;
  84566. }
  84567. return false;
  84568. };
  84569. /**
  84570. * Returns true if the mesh should render, otherwise false.
  84571. * @param mesh The mesh to render
  84572. * @returns true if it should render otherwise false
  84573. */
  84574. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84575. // Excluded Mesh
  84576. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84577. return false;
  84578. }
  84579. ;
  84580. return true;
  84581. };
  84582. /**
  84583. * Sets the required values for both the emissive texture and and the main color.
  84584. */
  84585. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84586. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84587. if (highlightLayerMesh) {
  84588. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84589. }
  84590. else {
  84591. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84592. }
  84593. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84594. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84595. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84596. }
  84597. else {
  84598. this._emissiveTextureAndColor.texture = null;
  84599. }
  84600. };
  84601. /**
  84602. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84603. * @param mesh The mesh to exclude from the highlight layer
  84604. */
  84605. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84606. if (!this._excludedMeshes) {
  84607. return;
  84608. }
  84609. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84610. if (!meshExcluded) {
  84611. this._excludedMeshes[mesh.uniqueId] = {
  84612. mesh: mesh,
  84613. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84614. mesh.getEngine().setStencilBuffer(false);
  84615. }),
  84616. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84617. mesh.getEngine().setStencilBuffer(true);
  84618. }),
  84619. };
  84620. }
  84621. };
  84622. /**
  84623. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84624. * @param mesh The mesh to highlight
  84625. */
  84626. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84627. if (!this._excludedMeshes) {
  84628. return;
  84629. }
  84630. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84631. if (meshExcluded) {
  84632. if (meshExcluded.beforeRender) {
  84633. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84634. }
  84635. if (meshExcluded.afterRender) {
  84636. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84637. }
  84638. }
  84639. this._excludedMeshes[mesh.uniqueId] = null;
  84640. };
  84641. /**
  84642. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84643. * @param mesh mesh to test
  84644. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84645. */
  84646. HighlightLayer.prototype.hasMesh = function (mesh) {
  84647. if (!this._meshes) {
  84648. return false;
  84649. }
  84650. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84651. };
  84652. /**
  84653. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84654. * @param mesh The mesh to highlight
  84655. * @param color The color of the highlight
  84656. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84657. */
  84658. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84659. var _this = this;
  84660. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84661. if (!this._meshes) {
  84662. return;
  84663. }
  84664. var meshHighlight = this._meshes[mesh.uniqueId];
  84665. if (meshHighlight) {
  84666. meshHighlight.color = color;
  84667. }
  84668. else {
  84669. this._meshes[mesh.uniqueId] = {
  84670. mesh: mesh,
  84671. color: color,
  84672. // Lambda required for capture due to Observable this context
  84673. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84674. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84675. _this._defaultStencilReference(mesh);
  84676. }
  84677. else {
  84678. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84679. }
  84680. }),
  84681. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84682. glowEmissiveOnly: glowEmissiveOnly
  84683. };
  84684. }
  84685. this._shouldRender = true;
  84686. };
  84687. /**
  84688. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84689. * @param mesh The mesh to highlight
  84690. */
  84691. HighlightLayer.prototype.removeMesh = function (mesh) {
  84692. if (!this._meshes) {
  84693. return;
  84694. }
  84695. var meshHighlight = this._meshes[mesh.uniqueId];
  84696. if (meshHighlight) {
  84697. if (meshHighlight.observerHighlight) {
  84698. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84699. }
  84700. if (meshHighlight.observerDefault) {
  84701. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84702. }
  84703. delete this._meshes[mesh.uniqueId];
  84704. }
  84705. this._shouldRender = false;
  84706. for (var meshHighlightToCheck in this._meshes) {
  84707. if (this._meshes[meshHighlightToCheck]) {
  84708. this._shouldRender = true;
  84709. break;
  84710. }
  84711. }
  84712. };
  84713. /**
  84714. * Force the stencil to the normal expected value for none glowing parts
  84715. */
  84716. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84717. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84718. };
  84719. /**
  84720. * Free any resources and references associated to a mesh.
  84721. * Internal use
  84722. * @param mesh The mesh to free.
  84723. */
  84724. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84725. this.removeMesh(mesh);
  84726. this.removeExcludedMesh(mesh);
  84727. };
  84728. /**
  84729. * Dispose the highlight layer and free resources.
  84730. */
  84731. HighlightLayer.prototype.dispose = function () {
  84732. if (this._meshes) {
  84733. // Clean mesh references
  84734. for (var id in this._meshes) {
  84735. var meshHighlight = this._meshes[id];
  84736. if (meshHighlight && meshHighlight.mesh) {
  84737. if (meshHighlight.observerHighlight) {
  84738. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84739. }
  84740. if (meshHighlight.observerDefault) {
  84741. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84742. }
  84743. }
  84744. }
  84745. this._meshes = null;
  84746. }
  84747. if (this._excludedMeshes) {
  84748. for (var id in this._excludedMeshes) {
  84749. var meshHighlight = this._excludedMeshes[id];
  84750. if (meshHighlight) {
  84751. if (meshHighlight.beforeRender) {
  84752. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84753. }
  84754. if (meshHighlight.afterRender) {
  84755. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84756. }
  84757. }
  84758. }
  84759. this._excludedMeshes = null;
  84760. }
  84761. _super.prototype.dispose.call(this);
  84762. };
  84763. /**
  84764. * Effect Name of the highlight layer.
  84765. */
  84766. HighlightLayer.EffectName = "HighlightLayer";
  84767. /**
  84768. * The neutral color used during the preparation of the glow effect.
  84769. * This is black by default as the blend operation is a blend operation.
  84770. */
  84771. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84772. /**
  84773. * Stencil value used for glowing meshes.
  84774. */
  84775. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84776. /**
  84777. * Stencil value used for the other meshes in the scene.
  84778. */
  84779. HighlightLayer.NormalMeshStencilReference = 0x01;
  84780. return HighlightLayer;
  84781. }(BABYLON.EffectLayer));
  84782. BABYLON.HighlightLayer = HighlightLayer;
  84783. })(BABYLON || (BABYLON = {}));
  84784. //# sourceMappingURL=babylon.highlightLayer.js.map
  84785. var BABYLON;
  84786. (function (BABYLON) {
  84787. /**
  84788. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84789. *
  84790. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84791. * glowy meshes to your scene.
  84792. *
  84793. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84794. */
  84795. var GlowLayer = /** @class */ (function (_super) {
  84796. __extends(GlowLayer, _super);
  84797. /**
  84798. * Instantiates a new glow Layer and references it to the scene.
  84799. * @param name The name of the layer
  84800. * @param scene The scene to use the layer in
  84801. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84802. */
  84803. function GlowLayer(name, scene, options) {
  84804. var _this = _super.call(this, name, scene) || this;
  84805. _this.name = name;
  84806. _this._intensity = 1.0;
  84807. _this._includedOnlyMeshes = [];
  84808. _this._excludedMeshes = [];
  84809. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84810. // Adapt options
  84811. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84812. // Initialize the layer
  84813. _this._init({
  84814. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84815. camera: _this._options.camera,
  84816. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84817. mainTextureRatio: _this._options.mainTextureRatio
  84818. });
  84819. return _this;
  84820. }
  84821. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84822. /**
  84823. * Gets the kernel size of the blur.
  84824. */
  84825. get: function () {
  84826. return this._horizontalBlurPostprocess1.kernel;
  84827. },
  84828. /**
  84829. * Sets the kernel size of the blur.
  84830. */
  84831. set: function (value) {
  84832. this._horizontalBlurPostprocess1.kernel = value;
  84833. this._verticalBlurPostprocess1.kernel = value;
  84834. this._horizontalBlurPostprocess2.kernel = value;
  84835. this._verticalBlurPostprocess2.kernel = value;
  84836. },
  84837. enumerable: true,
  84838. configurable: true
  84839. });
  84840. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84841. /**
  84842. * Gets the glow intensity.
  84843. */
  84844. get: function () {
  84845. return this._intensity;
  84846. },
  84847. /**
  84848. * Sets the glow intensity.
  84849. */
  84850. set: function (value) {
  84851. this._intensity = value;
  84852. },
  84853. enumerable: true,
  84854. configurable: true
  84855. });
  84856. /**
  84857. * Get the effect name of the layer.
  84858. * @return The effect name
  84859. */
  84860. GlowLayer.prototype.getEffectName = function () {
  84861. return GlowLayer.EffectName;
  84862. };
  84863. /**
  84864. * Create the merge effect. This is the shader use to blit the information back
  84865. * to the main canvas at the end of the scene rendering.
  84866. */
  84867. GlowLayer.prototype._createMergeEffect = function () {
  84868. // Effect
  84869. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84870. };
  84871. /**
  84872. * Creates the render target textures and post processes used in the glow layer.
  84873. */
  84874. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84875. var _this = this;
  84876. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84877. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84878. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84879. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84880. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84881. width: blurTextureWidth,
  84882. height: blurTextureHeight
  84883. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84884. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84885. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84886. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84887. this._blurTexture1.renderParticles = false;
  84888. this._blurTexture1.ignoreCameraViewport = true;
  84889. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84890. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84891. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84892. width: blurTextureWidth2,
  84893. height: blurTextureHeight2
  84894. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84895. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84896. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84897. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84898. this._blurTexture2.renderParticles = false;
  84899. this._blurTexture2.ignoreCameraViewport = true;
  84900. this._textures = [this._blurTexture1, this._blurTexture2];
  84901. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84902. width: blurTextureWidth,
  84903. height: blurTextureHeight
  84904. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84905. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84906. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84907. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84908. effect.setTexture("textureSampler", _this._mainTexture);
  84909. });
  84910. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84911. width: blurTextureWidth,
  84912. height: blurTextureHeight
  84913. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84914. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84915. width: blurTextureWidth2,
  84916. height: blurTextureHeight2
  84917. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84918. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84919. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84920. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84921. effect.setTexture("textureSampler", _this._blurTexture1);
  84922. });
  84923. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84924. width: blurTextureWidth2,
  84925. height: blurTextureHeight2
  84926. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84927. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84928. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84929. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84930. this._mainTexture.samples = this._options.mainTextureSamples;
  84931. this._mainTexture.onAfterUnbindObservable.add(function () {
  84932. var internalTexture = _this._blurTexture1.getInternalTexture();
  84933. if (internalTexture) {
  84934. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84935. internalTexture = _this._blurTexture2.getInternalTexture();
  84936. if (internalTexture) {
  84937. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84938. }
  84939. }
  84940. });
  84941. // Prevent autoClear.
  84942. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84943. };
  84944. /**
  84945. * Checks for the readiness of the element composing the layer.
  84946. * @param subMesh the mesh to check for
  84947. * @param useInstances specify wether or not to use instances to render the mesh
  84948. * @param emissiveTexture the associated emissive texture used to generate the glow
  84949. * @return true if ready otherwise, false
  84950. */
  84951. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84952. var material = subMesh.getMaterial();
  84953. var mesh = subMesh.getRenderingMesh();
  84954. if (!material || !mesh) {
  84955. return false;
  84956. }
  84957. var emissiveTexture = material.emissiveTexture;
  84958. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84959. };
  84960. /**
  84961. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84962. */
  84963. GlowLayer.prototype.needStencil = function () {
  84964. return false;
  84965. };
  84966. /**
  84967. * Implementation specific of rendering the generating effect on the main canvas.
  84968. * @param effect The effect used to render through
  84969. */
  84970. GlowLayer.prototype._internalRender = function (effect) {
  84971. // Texture
  84972. effect.setTexture("textureSampler", this._blurTexture1);
  84973. effect.setTexture("textureSampler2", this._blurTexture2);
  84974. effect.setFloat("offset", this._intensity);
  84975. // Cache
  84976. var engine = this._engine;
  84977. var previousStencilBuffer = engine.getStencilBuffer();
  84978. // Draw order
  84979. engine.setStencilBuffer(false);
  84980. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84981. // Draw order
  84982. engine.setStencilBuffer(previousStencilBuffer);
  84983. };
  84984. /**
  84985. * Sets the required values for both the emissive texture and and the main color.
  84986. */
  84987. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84988. var textureLevel = 1.0;
  84989. if (this.customEmissiveTextureSelector) {
  84990. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84991. }
  84992. else {
  84993. if (material) {
  84994. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84995. if (this._emissiveTextureAndColor.texture) {
  84996. textureLevel = this._emissiveTextureAndColor.texture.level;
  84997. }
  84998. }
  84999. else {
  85000. this._emissiveTextureAndColor.texture = null;
  85001. }
  85002. }
  85003. if (this.customEmissiveColorSelector) {
  85004. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85005. }
  85006. else {
  85007. if (material.emissiveColor) {
  85008. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85009. }
  85010. else {
  85011. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85012. }
  85013. }
  85014. };
  85015. /**
  85016. * Returns true if the mesh should render, otherwise false.
  85017. * @param mesh The mesh to render
  85018. * @returns true if it should render otherwise false
  85019. */
  85020. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85021. return this.hasMesh(mesh);
  85022. };
  85023. /**
  85024. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85025. * @param mesh The mesh to exclude from the glow layer
  85026. */
  85027. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85028. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85029. this._excludedMeshes.push(mesh.uniqueId);
  85030. }
  85031. };
  85032. /**
  85033. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85034. * @param mesh The mesh to remove
  85035. */
  85036. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85037. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85038. if (index !== -1) {
  85039. this._excludedMeshes.splice(index, 1);
  85040. }
  85041. };
  85042. /**
  85043. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85044. * @param mesh The mesh to include in the glow layer
  85045. */
  85046. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85047. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85048. this._includedOnlyMeshes.push(mesh.uniqueId);
  85049. }
  85050. };
  85051. /**
  85052. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85053. * @param mesh The mesh to remove
  85054. */
  85055. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85056. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85057. if (index !== -1) {
  85058. this._includedOnlyMeshes.splice(index, 1);
  85059. }
  85060. };
  85061. /**
  85062. * Determine if a given mesh will be used in the glow layer
  85063. * @param mesh The mesh to test
  85064. * @returns true if the mesh will be highlighted by the current glow layer
  85065. */
  85066. GlowLayer.prototype.hasMesh = function (mesh) {
  85067. // Included Mesh
  85068. if (this._includedOnlyMeshes.length) {
  85069. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85070. }
  85071. ;
  85072. // Excluded Mesh
  85073. if (this._excludedMeshes.length) {
  85074. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85075. }
  85076. ;
  85077. return true;
  85078. };
  85079. /**
  85080. * Free any resources and references associated to a mesh.
  85081. * Internal use
  85082. * @param mesh The mesh to free.
  85083. */
  85084. GlowLayer.prototype._disposeMesh = function (mesh) {
  85085. this.removeIncludedOnlyMesh(mesh);
  85086. this.removeExcludedMesh(mesh);
  85087. };
  85088. /**
  85089. * Effect Name of the layer.
  85090. */
  85091. GlowLayer.EffectName = "GlowLayer";
  85092. /**
  85093. * The default blur kernel size used for the glow.
  85094. */
  85095. GlowLayer.DefaultBlurKernelSize = 32;
  85096. /**
  85097. * The default texture size ratio used for the glow.
  85098. */
  85099. GlowLayer.DefaultTextureRatio = 0.5;
  85100. return GlowLayer;
  85101. }(BABYLON.EffectLayer));
  85102. BABYLON.GlowLayer = GlowLayer;
  85103. })(BABYLON || (BABYLON = {}));
  85104. //# sourceMappingURL=babylon.glowLayer.js.map
  85105. var BABYLON;
  85106. (function (BABYLON) {
  85107. /**
  85108. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85109. */
  85110. var AssetTaskState;
  85111. (function (AssetTaskState) {
  85112. /**
  85113. * Initialization
  85114. */
  85115. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85116. /**
  85117. * Running
  85118. */
  85119. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85120. /**
  85121. * Done
  85122. */
  85123. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85124. /**
  85125. * Error
  85126. */
  85127. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85128. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85129. /**
  85130. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85131. */
  85132. var AbstractAssetTask = /** @class */ (function () {
  85133. /**
  85134. * Creates a new {BABYLON.AssetsManager}
  85135. * @param name defines the name of the task
  85136. */
  85137. function AbstractAssetTask(
  85138. /**
  85139. * Task name
  85140. */ name) {
  85141. this.name = name;
  85142. this._isCompleted = false;
  85143. this._taskState = AssetTaskState.INIT;
  85144. }
  85145. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85146. /**
  85147. * Get if the task is completed
  85148. */
  85149. get: function () {
  85150. return this._isCompleted;
  85151. },
  85152. enumerable: true,
  85153. configurable: true
  85154. });
  85155. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85156. /**
  85157. * Gets the current state of the task
  85158. */
  85159. get: function () {
  85160. return this._taskState;
  85161. },
  85162. enumerable: true,
  85163. configurable: true
  85164. });
  85165. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85166. /**
  85167. * Gets the current error object (if task is in error)
  85168. */
  85169. get: function () {
  85170. return this._errorObject;
  85171. },
  85172. enumerable: true,
  85173. configurable: true
  85174. });
  85175. /**
  85176. * Internal only
  85177. * @ignore
  85178. */
  85179. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85180. if (this._errorObject) {
  85181. return;
  85182. }
  85183. this._errorObject = {
  85184. message: message,
  85185. exception: exception
  85186. };
  85187. };
  85188. /**
  85189. * Execute the current task
  85190. * @param scene defines the scene where you want your assets to be loaded
  85191. * @param onSuccess is a callback called when the task is successfully executed
  85192. * @param onError is a callback called if an error occurs
  85193. */
  85194. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85195. var _this = this;
  85196. this._taskState = AssetTaskState.RUNNING;
  85197. this.runTask(scene, function () {
  85198. _this.onDoneCallback(onSuccess, onError);
  85199. }, function (msg, exception) {
  85200. _this.onErrorCallback(onError, msg, exception);
  85201. });
  85202. };
  85203. /**
  85204. * Execute the current task
  85205. * @param scene defines the scene where you want your assets to be loaded
  85206. * @param onSuccess is a callback called when the task is successfully executed
  85207. * @param onError is a callback called if an error occurs
  85208. */
  85209. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85210. throw new Error("runTask is not implemented");
  85211. };
  85212. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85213. this._taskState = AssetTaskState.ERROR;
  85214. this._errorObject = {
  85215. message: message,
  85216. exception: exception
  85217. };
  85218. if (this.onError) {
  85219. this.onError(this, message, exception);
  85220. }
  85221. onError();
  85222. };
  85223. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85224. try {
  85225. this._taskState = AssetTaskState.DONE;
  85226. this._isCompleted = true;
  85227. if (this.onSuccess) {
  85228. this.onSuccess(this);
  85229. }
  85230. onSuccess();
  85231. }
  85232. catch (e) {
  85233. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85234. }
  85235. };
  85236. return AbstractAssetTask;
  85237. }());
  85238. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85239. /**
  85240. * Class used to share progress information about assets loading
  85241. */
  85242. var AssetsProgressEvent = /** @class */ (function () {
  85243. /**
  85244. * Creates a {BABYLON.AssetsProgressEvent}
  85245. * @param remainingCount defines the number of remaining tasks to process
  85246. * @param totalCount defines the total number of tasks
  85247. * @param task defines the task that was just processed
  85248. */
  85249. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85250. this.remainingCount = remainingCount;
  85251. this.totalCount = totalCount;
  85252. this.task = task;
  85253. }
  85254. return AssetsProgressEvent;
  85255. }());
  85256. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85257. /**
  85258. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85259. */
  85260. var MeshAssetTask = /** @class */ (function (_super) {
  85261. __extends(MeshAssetTask, _super);
  85262. /**
  85263. * Creates a new {BABYLON.MeshAssetTask}
  85264. * @param name defines the name of the task
  85265. * @param meshesNames defines the list of mesh's names you want to load
  85266. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85267. * @param sceneFilename defines the filename of the scene to load from
  85268. */
  85269. function MeshAssetTask(
  85270. /**
  85271. * Defines the name of the task
  85272. */
  85273. name,
  85274. /**
  85275. * Defines the list of mesh's names you want to load
  85276. */
  85277. meshesNames,
  85278. /**
  85279. * Defines the root url to use as a base to load your meshes and associated resources
  85280. */
  85281. rootUrl,
  85282. /**
  85283. * Defines the filename of the scene to load from
  85284. */
  85285. sceneFilename) {
  85286. var _this = _super.call(this, name) || this;
  85287. _this.name = name;
  85288. _this.meshesNames = meshesNames;
  85289. _this.rootUrl = rootUrl;
  85290. _this.sceneFilename = sceneFilename;
  85291. return _this;
  85292. }
  85293. /**
  85294. * Execute the current task
  85295. * @param scene defines the scene where you want your assets to be loaded
  85296. * @param onSuccess is a callback called when the task is successfully executed
  85297. * @param onError is a callback called if an error occurs
  85298. */
  85299. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85300. var _this = this;
  85301. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85302. _this.loadedMeshes = meshes;
  85303. _this.loadedParticleSystems = particleSystems;
  85304. _this.loadedSkeletons = skeletons;
  85305. onSuccess();
  85306. }, null, function (scene, message, exception) {
  85307. onError(message, exception);
  85308. });
  85309. };
  85310. return MeshAssetTask;
  85311. }(AbstractAssetTask));
  85312. BABYLON.MeshAssetTask = MeshAssetTask;
  85313. /**
  85314. * Define a task used by {BABYLON.AssetsManager} to load text content
  85315. */
  85316. var TextFileAssetTask = /** @class */ (function (_super) {
  85317. __extends(TextFileAssetTask, _super);
  85318. /**
  85319. * Creates a new TextFileAssetTask object
  85320. * @param name defines the name of the task
  85321. * @param url defines the location of the file to load
  85322. */
  85323. function TextFileAssetTask(
  85324. /**
  85325. * Defines the name of the task
  85326. */
  85327. name,
  85328. /**
  85329. * Defines the location of the file to load
  85330. */
  85331. url) {
  85332. var _this = _super.call(this, name) || this;
  85333. _this.name = name;
  85334. _this.url = url;
  85335. return _this;
  85336. }
  85337. /**
  85338. * Execute the current task
  85339. * @param scene defines the scene where you want your assets to be loaded
  85340. * @param onSuccess is a callback called when the task is successfully executed
  85341. * @param onError is a callback called if an error occurs
  85342. */
  85343. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85344. var _this = this;
  85345. scene._loadFile(this.url, function (data) {
  85346. _this.text = data;
  85347. onSuccess();
  85348. }, undefined, false, false, function (request, exception) {
  85349. if (request) {
  85350. onError(request.status + " " + request.statusText, exception);
  85351. }
  85352. });
  85353. };
  85354. return TextFileAssetTask;
  85355. }(AbstractAssetTask));
  85356. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85357. /**
  85358. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85359. */
  85360. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85361. __extends(BinaryFileAssetTask, _super);
  85362. /**
  85363. * Creates a new BinaryFileAssetTask object
  85364. * @param name defines the name of the new task
  85365. * @param url defines the location of the file to load
  85366. */
  85367. function BinaryFileAssetTask(
  85368. /**
  85369. * Defines the name of the task
  85370. */
  85371. name,
  85372. /**
  85373. * Defines the location of the file to load
  85374. */
  85375. url) {
  85376. var _this = _super.call(this, name) || this;
  85377. _this.name = name;
  85378. _this.url = url;
  85379. return _this;
  85380. }
  85381. /**
  85382. * Execute the current task
  85383. * @param scene defines the scene where you want your assets to be loaded
  85384. * @param onSuccess is a callback called when the task is successfully executed
  85385. * @param onError is a callback called if an error occurs
  85386. */
  85387. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85388. var _this = this;
  85389. scene._loadFile(this.url, function (data) {
  85390. _this.data = data;
  85391. onSuccess();
  85392. }, undefined, true, true, function (request, exception) {
  85393. if (request) {
  85394. onError(request.status + " " + request.statusText, exception);
  85395. }
  85396. });
  85397. };
  85398. return BinaryFileAssetTask;
  85399. }(AbstractAssetTask));
  85400. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85401. /**
  85402. * Define a task used by {BABYLON.AssetsManager} to load images
  85403. */
  85404. var ImageAssetTask = /** @class */ (function (_super) {
  85405. __extends(ImageAssetTask, _super);
  85406. /**
  85407. * Creates a new ImageAssetTask
  85408. * @param name defines the name of the task
  85409. * @param url defines the location of the image to load
  85410. */
  85411. function ImageAssetTask(
  85412. /**
  85413. * Defines the name of the task
  85414. */
  85415. name,
  85416. /**
  85417. * Defines the location of the image to load
  85418. */
  85419. url) {
  85420. var _this = _super.call(this, name) || this;
  85421. _this.name = name;
  85422. _this.url = url;
  85423. return _this;
  85424. }
  85425. /**
  85426. * Execute the current task
  85427. * @param scene defines the scene where you want your assets to be loaded
  85428. * @param onSuccess is a callback called when the task is successfully executed
  85429. * @param onError is a callback called if an error occurs
  85430. */
  85431. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85432. var _this = this;
  85433. var img = new Image();
  85434. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85435. img.onload = function () {
  85436. _this.image = img;
  85437. onSuccess();
  85438. };
  85439. img.onerror = function (err) {
  85440. onError("Error loading image", err);
  85441. };
  85442. img.src = this.url;
  85443. };
  85444. return ImageAssetTask;
  85445. }(AbstractAssetTask));
  85446. BABYLON.ImageAssetTask = ImageAssetTask;
  85447. /**
  85448. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85449. */
  85450. var TextureAssetTask = /** @class */ (function (_super) {
  85451. __extends(TextureAssetTask, _super);
  85452. /**
  85453. * Creates a new TextureAssetTask object
  85454. * @param name defines the name of the task
  85455. * @param url defines the location of the file to load
  85456. * @param noMipmap defines if mipmap should not be generated (default is false)
  85457. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85458. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85459. */
  85460. function TextureAssetTask(
  85461. /**
  85462. * Defines the name of the task
  85463. */
  85464. name,
  85465. /**
  85466. * Defines the location of the file to load
  85467. */
  85468. url,
  85469. /**
  85470. * Defines if mipmap should not be generated (default is false)
  85471. */
  85472. noMipmap,
  85473. /**
  85474. * Defines if texture must be inverted on Y axis (default is false)
  85475. */
  85476. invertY,
  85477. /**
  85478. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85479. */
  85480. samplingMode) {
  85481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85482. var _this = _super.call(this, name) || this;
  85483. _this.name = name;
  85484. _this.url = url;
  85485. _this.noMipmap = noMipmap;
  85486. _this.invertY = invertY;
  85487. _this.samplingMode = samplingMode;
  85488. return _this;
  85489. }
  85490. /**
  85491. * Execute the current task
  85492. * @param scene defines the scene where you want your assets to be loaded
  85493. * @param onSuccess is a callback called when the task is successfully executed
  85494. * @param onError is a callback called if an error occurs
  85495. */
  85496. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85497. var onload = function () {
  85498. onSuccess();
  85499. };
  85500. var onerror = function (message, exception) {
  85501. onError(message, exception);
  85502. };
  85503. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85504. };
  85505. return TextureAssetTask;
  85506. }(AbstractAssetTask));
  85507. BABYLON.TextureAssetTask = TextureAssetTask;
  85508. /**
  85509. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85510. */
  85511. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85512. __extends(CubeTextureAssetTask, _super);
  85513. /**
  85514. * Creates a new CubeTextureAssetTask
  85515. * @param name defines the name of the task
  85516. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85517. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85518. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85519. * @param files defines the explicit list of files (undefined by default)
  85520. */
  85521. function CubeTextureAssetTask(
  85522. /**
  85523. * Defines the name of the task
  85524. */
  85525. name,
  85526. /**
  85527. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85528. */
  85529. url,
  85530. /**
  85531. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85532. */
  85533. extensions,
  85534. /**
  85535. * Defines if mipmaps should not be generated (default is false)
  85536. */
  85537. noMipmap,
  85538. /**
  85539. * Defines the explicit list of files (undefined by default)
  85540. */
  85541. files) {
  85542. var _this = _super.call(this, name) || this;
  85543. _this.name = name;
  85544. _this.url = url;
  85545. _this.extensions = extensions;
  85546. _this.noMipmap = noMipmap;
  85547. _this.files = files;
  85548. return _this;
  85549. }
  85550. /**
  85551. * Execute the current task
  85552. * @param scene defines the scene where you want your assets to be loaded
  85553. * @param onSuccess is a callback called when the task is successfully executed
  85554. * @param onError is a callback called if an error occurs
  85555. */
  85556. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85557. var onload = function () {
  85558. onSuccess();
  85559. };
  85560. var onerror = function (message, exception) {
  85561. onError(message, exception);
  85562. };
  85563. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85564. };
  85565. return CubeTextureAssetTask;
  85566. }(AbstractAssetTask));
  85567. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85568. /**
  85569. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85570. */
  85571. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85572. __extends(HDRCubeTextureAssetTask, _super);
  85573. /**
  85574. * Creates a new HDRCubeTextureAssetTask object
  85575. * @param name defines the name of the task
  85576. * @param url defines the location of the file to load
  85577. * @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.
  85578. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85579. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85580. * @param useInGammaSpace 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)
  85581. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85582. */
  85583. function HDRCubeTextureAssetTask(
  85584. /**
  85585. * Defines the name of the task
  85586. */
  85587. name,
  85588. /**
  85589. * Defines the location of the file to load
  85590. */
  85591. url,
  85592. /**
  85593. * 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.
  85594. */
  85595. size,
  85596. /**
  85597. * Defines if mipmaps should not be generated (default is false)
  85598. */
  85599. noMipmap,
  85600. /**
  85601. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85602. */
  85603. generateHarmonics,
  85604. /**
  85605. * 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)
  85606. */
  85607. useInGammaSpace,
  85608. /**
  85609. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85610. */
  85611. usePMREMGenerator) {
  85612. if (noMipmap === void 0) { noMipmap = false; }
  85613. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85614. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85615. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85616. var _this = _super.call(this, name) || this;
  85617. _this.name = name;
  85618. _this.url = url;
  85619. _this.size = size;
  85620. _this.noMipmap = noMipmap;
  85621. _this.generateHarmonics = generateHarmonics;
  85622. _this.useInGammaSpace = useInGammaSpace;
  85623. _this.usePMREMGenerator = usePMREMGenerator;
  85624. return _this;
  85625. }
  85626. /**
  85627. * Execute the current task
  85628. * @param scene defines the scene where you want your assets to be loaded
  85629. * @param onSuccess is a callback called when the task is successfully executed
  85630. * @param onError is a callback called if an error occurs
  85631. */
  85632. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85633. var onload = function () {
  85634. onSuccess();
  85635. };
  85636. var onerror = function (message, exception) {
  85637. onError(message, exception);
  85638. };
  85639. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85640. };
  85641. return HDRCubeTextureAssetTask;
  85642. }(AbstractAssetTask));
  85643. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85644. /**
  85645. * This class can be used to easily import assets into a scene
  85646. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85647. */
  85648. var AssetsManager = /** @class */ (function () {
  85649. /**
  85650. * Creates a new AssetsManager
  85651. * @param scene defines the scene to work on
  85652. */
  85653. function AssetsManager(scene) {
  85654. this._isLoading = false;
  85655. this._tasks = new Array();
  85656. this._waitingTasksCount = 0;
  85657. this._totalTasksCount = 0;
  85658. /**
  85659. * Observable called when all tasks are processed
  85660. */
  85661. this.onTaskSuccessObservable = new BABYLON.Observable();
  85662. /**
  85663. * Observable called when a task had an error
  85664. */
  85665. this.onTaskErrorObservable = new BABYLON.Observable();
  85666. /**
  85667. * Observable called when a task is successful
  85668. */
  85669. this.onTasksDoneObservable = new BABYLON.Observable();
  85670. /**
  85671. * Observable called when a task is done (whatever the result is)
  85672. */
  85673. this.onProgressObservable = new BABYLON.Observable();
  85674. /**
  85675. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85676. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85677. */
  85678. this.useDefaultLoadingScreen = true;
  85679. this._scene = scene;
  85680. }
  85681. /**
  85682. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85683. * @param taskName defines the name of the new task
  85684. * @param meshesNames defines the name of meshes to load
  85685. * @param rootUrl defines the root url to use to locate files
  85686. * @param sceneFilename defines the filename of the scene file
  85687. * @returns a new {BABYLON.MeshAssetTask} object
  85688. */
  85689. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85690. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85691. this._tasks.push(task);
  85692. return task;
  85693. };
  85694. /**
  85695. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85696. * @param taskName defines the name of the new task
  85697. * @param url defines the url of the file to load
  85698. * @returns a new {BABYLON.TextFileAssetTask} object
  85699. */
  85700. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85701. var task = new TextFileAssetTask(taskName, url);
  85702. this._tasks.push(task);
  85703. return task;
  85704. };
  85705. /**
  85706. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85707. * @param taskName defines the name of the new task
  85708. * @param url defines the url of the file to load
  85709. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85710. */
  85711. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85712. var task = new BinaryFileAssetTask(taskName, url);
  85713. this._tasks.push(task);
  85714. return task;
  85715. };
  85716. /**
  85717. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85718. * @param taskName defines the name of the new task
  85719. * @param url defines the url of the file to load
  85720. * @returns a new {BABYLON.ImageAssetTask} object
  85721. */
  85722. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85723. var task = new ImageAssetTask(taskName, url);
  85724. this._tasks.push(task);
  85725. return task;
  85726. };
  85727. /**
  85728. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85729. * @param taskName defines the name of the new task
  85730. * @param url defines the url of the file to load
  85731. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85732. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85733. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85734. * @returns a new {BABYLON.TextureAssetTask} object
  85735. */
  85736. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85738. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85739. this._tasks.push(task);
  85740. return task;
  85741. };
  85742. /**
  85743. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85744. * @param taskName defines the name of the new task
  85745. * @param url defines the url of the file to load
  85746. * @param extensions defines the extension to use to load the cube map (can be null)
  85747. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85748. * @param files defines the list of files to load (can be null)
  85749. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85750. */
  85751. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85752. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85753. this._tasks.push(task);
  85754. return task;
  85755. };
  85756. /**
  85757. *
  85758. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85759. * @param taskName defines the name of the new task
  85760. * @param url defines the url of the file to load
  85761. * @param size defines the size you want for the cubemap (can be null)
  85762. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85763. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85764. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85765. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85766. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85767. */
  85768. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85769. if (noMipmap === void 0) { noMipmap = false; }
  85770. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85771. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85772. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85773. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85774. this._tasks.push(task);
  85775. return task;
  85776. };
  85777. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85778. var _this = this;
  85779. this._waitingTasksCount--;
  85780. try {
  85781. if (task.taskState === AssetTaskState.DONE) {
  85782. // Let's remove successfull tasks
  85783. BABYLON.Tools.SetImmediate(function () {
  85784. var index = _this._tasks.indexOf(task);
  85785. if (index > -1) {
  85786. _this._tasks.splice(index, 1);
  85787. }
  85788. });
  85789. }
  85790. if (this.onProgress) {
  85791. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85792. }
  85793. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85794. }
  85795. catch (e) {
  85796. BABYLON.Tools.Error("Error running progress callbacks.");
  85797. console.log(e);
  85798. }
  85799. if (this._waitingTasksCount === 0) {
  85800. try {
  85801. if (this.onFinish) {
  85802. this.onFinish(this._tasks);
  85803. }
  85804. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85805. }
  85806. catch (e) {
  85807. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85808. console.log(e);
  85809. }
  85810. this._isLoading = false;
  85811. this._scene.getEngine().hideLoadingUI();
  85812. }
  85813. };
  85814. AssetsManager.prototype._runTask = function (task) {
  85815. var _this = this;
  85816. var done = function () {
  85817. try {
  85818. if (_this.onTaskSuccess) {
  85819. _this.onTaskSuccess(task);
  85820. }
  85821. _this.onTaskSuccessObservable.notifyObservers(task);
  85822. _this._decreaseWaitingTasksCount(task);
  85823. }
  85824. catch (e) {
  85825. error("Error executing task success callbacks", e);
  85826. }
  85827. };
  85828. var error = function (message, exception) {
  85829. task._setErrorObject(message, exception);
  85830. if (_this.onTaskError) {
  85831. _this.onTaskError(task);
  85832. }
  85833. _this.onTaskErrorObservable.notifyObservers(task);
  85834. _this._decreaseWaitingTasksCount(task);
  85835. };
  85836. task.run(this._scene, done, error);
  85837. };
  85838. /**
  85839. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85840. * @return the current instance of the {BABYLON.AssetsManager}
  85841. */
  85842. AssetsManager.prototype.reset = function () {
  85843. this._isLoading = false;
  85844. this._tasks = new Array();
  85845. return this;
  85846. };
  85847. /**
  85848. * Start the loading process
  85849. * @return the current instance of the {BABYLON.AssetsManager}
  85850. */
  85851. AssetsManager.prototype.load = function () {
  85852. if (this._isLoading) {
  85853. return this;
  85854. }
  85855. this._isLoading = true;
  85856. this._waitingTasksCount = this._tasks.length;
  85857. this._totalTasksCount = this._tasks.length;
  85858. if (this._waitingTasksCount === 0) {
  85859. this._isLoading = false;
  85860. if (this.onFinish) {
  85861. this.onFinish(this._tasks);
  85862. }
  85863. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85864. return this;
  85865. }
  85866. if (this.useDefaultLoadingScreen) {
  85867. this._scene.getEngine().displayLoadingUI();
  85868. }
  85869. for (var index = 0; index < this._tasks.length; index++) {
  85870. var task = this._tasks[index];
  85871. this._runTask(task);
  85872. }
  85873. return this;
  85874. };
  85875. return AssetsManager;
  85876. }());
  85877. BABYLON.AssetsManager = AssetsManager;
  85878. })(BABYLON || (BABYLON = {}));
  85879. //# sourceMappingURL=babylon.assetsManager.js.map
  85880. var BABYLON;
  85881. (function (BABYLON) {
  85882. var serializedGeometries = [];
  85883. var serializeGeometry = function (geometry, serializationGeometries) {
  85884. if (serializedGeometries[geometry.id]) {
  85885. return;
  85886. }
  85887. if (geometry.doNotSerialize) {
  85888. return;
  85889. }
  85890. if (geometry instanceof BABYLON.BoxGeometry) {
  85891. serializationGeometries.boxes.push(geometry.serialize());
  85892. }
  85893. else if (geometry instanceof BABYLON.SphereGeometry) {
  85894. serializationGeometries.spheres.push(geometry.serialize());
  85895. }
  85896. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85897. serializationGeometries.cylinders.push(geometry.serialize());
  85898. }
  85899. else if (geometry instanceof BABYLON.TorusGeometry) {
  85900. serializationGeometries.toruses.push(geometry.serialize());
  85901. }
  85902. else if (geometry instanceof BABYLON.GroundGeometry) {
  85903. serializationGeometries.grounds.push(geometry.serialize());
  85904. }
  85905. else if (geometry instanceof BABYLON.Plane) {
  85906. serializationGeometries.planes.push(geometry.serialize());
  85907. }
  85908. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85909. serializationGeometries.torusKnots.push(geometry.serialize());
  85910. }
  85911. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85912. throw new Error("Unknown primitive type");
  85913. }
  85914. else {
  85915. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85916. }
  85917. serializedGeometries[geometry.id] = true;
  85918. };
  85919. var serializeMesh = function (mesh, serializationScene) {
  85920. var serializationObject = {};
  85921. // Geometry
  85922. var geometry = mesh._geometry;
  85923. if (geometry) {
  85924. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85925. // 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
  85926. serializeGeometry(geometry, serializationScene.geometries);
  85927. }
  85928. }
  85929. // Custom
  85930. if (mesh.serialize) {
  85931. mesh.serialize(serializationObject);
  85932. }
  85933. return serializationObject;
  85934. };
  85935. var finalizeSingleMesh = function (mesh, serializationObject) {
  85936. //only works if the mesh is already loaded
  85937. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85938. //serialize material
  85939. if (mesh.material) {
  85940. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85941. serializationObject.materials = serializationObject.materials || [];
  85942. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85943. serializationObject.materials.push(mesh.material.serialize());
  85944. }
  85945. }
  85946. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85947. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85948. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85949. serializationObject.multiMaterials.push(mesh.material.serialize());
  85950. }
  85951. }
  85952. }
  85953. //serialize geometry
  85954. var geometry = mesh._geometry;
  85955. if (geometry) {
  85956. if (!serializationObject.geometries) {
  85957. serializationObject.geometries = {};
  85958. serializationObject.geometries.boxes = [];
  85959. serializationObject.geometries.spheres = [];
  85960. serializationObject.geometries.cylinders = [];
  85961. serializationObject.geometries.toruses = [];
  85962. serializationObject.geometries.grounds = [];
  85963. serializationObject.geometries.planes = [];
  85964. serializationObject.geometries.torusKnots = [];
  85965. serializationObject.geometries.vertexData = [];
  85966. }
  85967. serializeGeometry(geometry, serializationObject.geometries);
  85968. }
  85969. // Skeletons
  85970. if (mesh.skeleton) {
  85971. serializationObject.skeletons = serializationObject.skeletons || [];
  85972. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85973. }
  85974. //serialize the actual mesh
  85975. serializationObject.meshes = serializationObject.meshes || [];
  85976. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85977. }
  85978. };
  85979. var SceneSerializer = /** @class */ (function () {
  85980. function SceneSerializer() {
  85981. }
  85982. SceneSerializer.ClearCache = function () {
  85983. serializedGeometries = [];
  85984. };
  85985. SceneSerializer.Serialize = function (scene) {
  85986. var serializationObject = {};
  85987. SceneSerializer.ClearCache();
  85988. // Scene
  85989. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85990. serializationObject.autoClear = scene.autoClear;
  85991. serializationObject.clearColor = scene.clearColor.asArray();
  85992. serializationObject.ambientColor = scene.ambientColor.asArray();
  85993. serializationObject.gravity = scene.gravity.asArray();
  85994. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85995. serializationObject.workerCollisions = scene.workerCollisions;
  85996. // Fog
  85997. if (scene.fogMode && scene.fogMode !== 0) {
  85998. serializationObject.fogMode = scene.fogMode;
  85999. serializationObject.fogColor = scene.fogColor.asArray();
  86000. serializationObject.fogStart = scene.fogStart;
  86001. serializationObject.fogEnd = scene.fogEnd;
  86002. serializationObject.fogDensity = scene.fogDensity;
  86003. }
  86004. //Physics
  86005. if (scene.isPhysicsEnabled()) {
  86006. var physicEngine = scene.getPhysicsEngine();
  86007. if (physicEngine) {
  86008. serializationObject.physicsEnabled = true;
  86009. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86010. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86011. }
  86012. }
  86013. // Metadata
  86014. if (scene.metadata) {
  86015. serializationObject.metadata = scene.metadata;
  86016. }
  86017. // Morph targets
  86018. serializationObject.morphTargetManagers = [];
  86019. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86020. var abstractMesh = _a[_i];
  86021. var manager = abstractMesh.morphTargetManager;
  86022. if (manager) {
  86023. serializationObject.morphTargetManagers.push(manager.serialize());
  86024. }
  86025. }
  86026. // Lights
  86027. serializationObject.lights = [];
  86028. var index;
  86029. var light;
  86030. for (index = 0; index < scene.lights.length; index++) {
  86031. light = scene.lights[index];
  86032. if (!light.doNotSerialize) {
  86033. serializationObject.lights.push(light.serialize());
  86034. }
  86035. }
  86036. // Cameras
  86037. serializationObject.cameras = [];
  86038. for (index = 0; index < scene.cameras.length; index++) {
  86039. var camera = scene.cameras[index];
  86040. if (!camera.doNotSerialize) {
  86041. serializationObject.cameras.push(camera.serialize());
  86042. }
  86043. }
  86044. if (scene.activeCamera) {
  86045. serializationObject.activeCameraID = scene.activeCamera.id;
  86046. }
  86047. // Animations
  86048. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86049. // Materials
  86050. serializationObject.materials = [];
  86051. serializationObject.multiMaterials = [];
  86052. var material;
  86053. for (index = 0; index < scene.materials.length; index++) {
  86054. material = scene.materials[index];
  86055. if (!material.doNotSerialize) {
  86056. serializationObject.materials.push(material.serialize());
  86057. }
  86058. }
  86059. // MultiMaterials
  86060. serializationObject.multiMaterials = [];
  86061. for (index = 0; index < scene.multiMaterials.length; index++) {
  86062. var multiMaterial = scene.multiMaterials[index];
  86063. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86064. }
  86065. // Environment texture
  86066. if (scene.environmentTexture) {
  86067. serializationObject.environmentTexture = scene.environmentTexture.name;
  86068. }
  86069. // Skeletons
  86070. serializationObject.skeletons = [];
  86071. for (index = 0; index < scene.skeletons.length; index++) {
  86072. var skeleton = scene.skeletons[index];
  86073. if (!skeleton.doNotSerialize) {
  86074. serializationObject.skeletons.push(skeleton.serialize());
  86075. }
  86076. }
  86077. // Transform nodes
  86078. serializationObject.transformNodes = [];
  86079. for (index = 0; index < scene.transformNodes.length; index++) {
  86080. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86081. }
  86082. // Geometries
  86083. serializationObject.geometries = {};
  86084. serializationObject.geometries.boxes = [];
  86085. serializationObject.geometries.spheres = [];
  86086. serializationObject.geometries.cylinders = [];
  86087. serializationObject.geometries.toruses = [];
  86088. serializationObject.geometries.grounds = [];
  86089. serializationObject.geometries.planes = [];
  86090. serializationObject.geometries.torusKnots = [];
  86091. serializationObject.geometries.vertexData = [];
  86092. serializedGeometries = [];
  86093. var geometries = scene.getGeometries();
  86094. for (index = 0; index < geometries.length; index++) {
  86095. var geometry = geometries[index];
  86096. if (geometry.isReady()) {
  86097. serializeGeometry(geometry, serializationObject.geometries);
  86098. }
  86099. }
  86100. // Meshes
  86101. serializationObject.meshes = [];
  86102. for (index = 0; index < scene.meshes.length; index++) {
  86103. var abstractMesh = scene.meshes[index];
  86104. if (abstractMesh instanceof BABYLON.Mesh) {
  86105. var mesh = abstractMesh;
  86106. if (!mesh.doNotSerialize) {
  86107. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86108. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86109. }
  86110. }
  86111. }
  86112. }
  86113. // Particles Systems
  86114. serializationObject.particleSystems = [];
  86115. for (index = 0; index < scene.particleSystems.length; index++) {
  86116. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86117. }
  86118. // Lens flares
  86119. serializationObject.lensFlareSystems = [];
  86120. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86121. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86122. }
  86123. // Shadows
  86124. serializationObject.shadowGenerators = [];
  86125. for (index = 0; index < scene.lights.length; index++) {
  86126. light = scene.lights[index];
  86127. var shadowGenerator = light.getShadowGenerator();
  86128. if (shadowGenerator) {
  86129. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86130. }
  86131. }
  86132. // Action Manager
  86133. if (scene.actionManager) {
  86134. serializationObject.actions = scene.actionManager.serialize("scene");
  86135. }
  86136. // Audio
  86137. serializationObject.sounds = [];
  86138. for (index = 0; index < scene.soundTracks.length; index++) {
  86139. var soundtrack = scene.soundTracks[index];
  86140. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86141. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86142. }
  86143. }
  86144. return serializationObject;
  86145. };
  86146. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86147. if (withParents === void 0) { withParents = false; }
  86148. if (withChildren === void 0) { withChildren = false; }
  86149. var serializationObject = {};
  86150. SceneSerializer.ClearCache();
  86151. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86152. if (withParents || withChildren) {
  86153. //deliberate for loop! not for each, appended should be processed as well.
  86154. for (var i = 0; i < toSerialize.length; ++i) {
  86155. if (withChildren) {
  86156. toSerialize[i].getDescendants().forEach(function (node) {
  86157. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86158. toSerialize.push(node);
  86159. }
  86160. });
  86161. }
  86162. //make sure the array doesn't contain the object already
  86163. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86164. toSerialize.push(toSerialize[i].parent);
  86165. }
  86166. }
  86167. }
  86168. toSerialize.forEach(function (mesh) {
  86169. finalizeSingleMesh(mesh, serializationObject);
  86170. });
  86171. return serializationObject;
  86172. };
  86173. return SceneSerializer;
  86174. }());
  86175. BABYLON.SceneSerializer = SceneSerializer;
  86176. })(BABYLON || (BABYLON = {}));
  86177. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86178. var BABYLON;
  86179. (function (BABYLON) {
  86180. var ReflectionProbe = /** @class */ (function () {
  86181. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86183. var _this = this;
  86184. this.name = name;
  86185. this._viewMatrix = BABYLON.Matrix.Identity();
  86186. this._target = BABYLON.Vector3.Zero();
  86187. this._add = BABYLON.Vector3.Zero();
  86188. this._invertYAxis = false;
  86189. this.position = BABYLON.Vector3.Zero();
  86190. this._scene = scene;
  86191. this._scene.reflectionProbes.push(this);
  86192. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86193. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86194. switch (faceIndex) {
  86195. case 0:
  86196. _this._add.copyFromFloats(1, 0, 0);
  86197. break;
  86198. case 1:
  86199. _this._add.copyFromFloats(-1, 0, 0);
  86200. break;
  86201. case 2:
  86202. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86203. break;
  86204. case 3:
  86205. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86206. break;
  86207. case 4:
  86208. _this._add.copyFromFloats(0, 0, 1);
  86209. break;
  86210. case 5:
  86211. _this._add.copyFromFloats(0, 0, -1);
  86212. break;
  86213. }
  86214. if (_this._attachedMesh) {
  86215. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86216. }
  86217. _this.position.addToRef(_this._add, _this._target);
  86218. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86219. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86220. scene._forcedViewPosition = _this.position;
  86221. });
  86222. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86223. scene._forcedViewPosition = null;
  86224. scene.updateTransformMatrix(true);
  86225. });
  86226. if (scene.activeCamera) {
  86227. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86228. }
  86229. }
  86230. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86231. get: function () {
  86232. return this._renderTargetTexture.samples;
  86233. },
  86234. set: function (value) {
  86235. this._renderTargetTexture.samples = value;
  86236. },
  86237. enumerable: true,
  86238. configurable: true
  86239. });
  86240. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86241. get: function () {
  86242. return this._renderTargetTexture.refreshRate;
  86243. },
  86244. set: function (value) {
  86245. this._renderTargetTexture.refreshRate = value;
  86246. },
  86247. enumerable: true,
  86248. configurable: true
  86249. });
  86250. ReflectionProbe.prototype.getScene = function () {
  86251. return this._scene;
  86252. };
  86253. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86254. get: function () {
  86255. return this._renderTargetTexture;
  86256. },
  86257. enumerable: true,
  86258. configurable: true
  86259. });
  86260. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86261. get: function () {
  86262. return this._renderTargetTexture.renderList;
  86263. },
  86264. enumerable: true,
  86265. configurable: true
  86266. });
  86267. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86268. this._attachedMesh = mesh;
  86269. };
  86270. /**
  86271. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86272. *
  86273. * @param renderingGroupId The rendering group id corresponding to its index
  86274. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86275. */
  86276. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86277. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86278. };
  86279. ReflectionProbe.prototype.dispose = function () {
  86280. var index = this._scene.reflectionProbes.indexOf(this);
  86281. if (index !== -1) {
  86282. // Remove from the scene if found
  86283. this._scene.reflectionProbes.splice(index, 1);
  86284. }
  86285. if (this._renderTargetTexture) {
  86286. this._renderTargetTexture.dispose();
  86287. this._renderTargetTexture = null;
  86288. }
  86289. };
  86290. return ReflectionProbe;
  86291. }());
  86292. BABYLON.ReflectionProbe = ReflectionProbe;
  86293. })(BABYLON || (BABYLON = {}));
  86294. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86295. var BABYLON;
  86296. (function (BABYLON) {
  86297. var Layer = /** @class */ (function () {
  86298. function Layer(name, imgUrl, scene, isBackground, color) {
  86299. this.name = name;
  86300. this.scale = new BABYLON.Vector2(1, 1);
  86301. this.offset = new BABYLON.Vector2(0, 0);
  86302. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86303. this.layerMask = 0x0FFFFFFF;
  86304. this._vertexBuffers = {};
  86305. // Events
  86306. /**
  86307. * An event triggered when the layer is disposed.
  86308. * @type {BABYLON.Observable}
  86309. */
  86310. this.onDisposeObservable = new BABYLON.Observable();
  86311. /**
  86312. * An event triggered before rendering the scene
  86313. * @type {BABYLON.Observable}
  86314. */
  86315. this.onBeforeRenderObservable = new BABYLON.Observable();
  86316. /**
  86317. * An event triggered after rendering the scene
  86318. * @type {BABYLON.Observable}
  86319. */
  86320. this.onAfterRenderObservable = new BABYLON.Observable();
  86321. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86322. this.isBackground = isBackground === undefined ? true : isBackground;
  86323. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86324. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86325. this._scene.layers.push(this);
  86326. var engine = this._scene.getEngine();
  86327. // VBO
  86328. var vertices = [];
  86329. vertices.push(1, 1);
  86330. vertices.push(-1, 1);
  86331. vertices.push(-1, -1);
  86332. vertices.push(1, -1);
  86333. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86334. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86335. this._createIndexBuffer();
  86336. // Effects
  86337. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86338. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86339. }
  86340. Object.defineProperty(Layer.prototype, "onDispose", {
  86341. set: function (callback) {
  86342. if (this._onDisposeObserver) {
  86343. this.onDisposeObservable.remove(this._onDisposeObserver);
  86344. }
  86345. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86346. },
  86347. enumerable: true,
  86348. configurable: true
  86349. });
  86350. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86351. set: function (callback) {
  86352. if (this._onBeforeRenderObserver) {
  86353. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86354. }
  86355. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86356. },
  86357. enumerable: true,
  86358. configurable: true
  86359. });
  86360. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86361. set: function (callback) {
  86362. if (this._onAfterRenderObserver) {
  86363. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86364. }
  86365. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86366. },
  86367. enumerable: true,
  86368. configurable: true
  86369. });
  86370. Layer.prototype._createIndexBuffer = function () {
  86371. var engine = this._scene.getEngine();
  86372. // Indices
  86373. var indices = [];
  86374. indices.push(0);
  86375. indices.push(1);
  86376. indices.push(2);
  86377. indices.push(0);
  86378. indices.push(2);
  86379. indices.push(3);
  86380. this._indexBuffer = engine.createIndexBuffer(indices);
  86381. };
  86382. Layer.prototype._rebuild = function () {
  86383. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86384. if (vb) {
  86385. vb._rebuild();
  86386. }
  86387. this._createIndexBuffer();
  86388. };
  86389. Layer.prototype.render = function () {
  86390. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86391. // Check
  86392. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86393. return;
  86394. var engine = this._scene.getEngine();
  86395. this.onBeforeRenderObservable.notifyObservers(this);
  86396. // Render
  86397. engine.enableEffect(currentEffect);
  86398. engine.setState(false);
  86399. // Texture
  86400. currentEffect.setTexture("textureSampler", this.texture);
  86401. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86402. // Color
  86403. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86404. // Scale / offset
  86405. currentEffect.setVector2("offset", this.offset);
  86406. currentEffect.setVector2("scale", this.scale);
  86407. // VBOs
  86408. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86409. // Draw order
  86410. if (!this.alphaTest) {
  86411. engine.setAlphaMode(this.alphaBlendingMode);
  86412. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86413. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86414. }
  86415. else {
  86416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86417. }
  86418. this.onAfterRenderObservable.notifyObservers(this);
  86419. };
  86420. Layer.prototype.dispose = function () {
  86421. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86422. if (vertexBuffer) {
  86423. vertexBuffer.dispose();
  86424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86425. }
  86426. if (this._indexBuffer) {
  86427. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86428. this._indexBuffer = null;
  86429. }
  86430. if (this.texture) {
  86431. this.texture.dispose();
  86432. this.texture = null;
  86433. }
  86434. // Remove from scene
  86435. var index = this._scene.layers.indexOf(this);
  86436. this._scene.layers.splice(index, 1);
  86437. // Callback
  86438. this.onDisposeObservable.notifyObservers(this);
  86439. this.onDisposeObservable.clear();
  86440. this.onAfterRenderObservable.clear();
  86441. this.onBeforeRenderObservable.clear();
  86442. };
  86443. return Layer;
  86444. }());
  86445. BABYLON.Layer = Layer;
  86446. })(BABYLON || (BABYLON = {}));
  86447. //# sourceMappingURL=babylon.layer.js.map
  86448. var BABYLON;
  86449. (function (BABYLON) {
  86450. var TextureTools = /** @class */ (function () {
  86451. function TextureTools() {
  86452. }
  86453. /**
  86454. * Uses the GPU to create a copy texture rescaled at a given size
  86455. * @param texture Texture to copy from
  86456. * @param width Desired width
  86457. * @param height Desired height
  86458. * @return Generated texture
  86459. */
  86460. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86461. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86462. var scene = texture.getScene();
  86463. var engine = scene.getEngine();
  86464. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86465. rtt.wrapU = texture.wrapU;
  86466. rtt.wrapV = texture.wrapV;
  86467. rtt.uOffset = texture.uOffset;
  86468. rtt.vOffset = texture.vOffset;
  86469. rtt.uScale = texture.uScale;
  86470. rtt.vScale = texture.vScale;
  86471. rtt.uAng = texture.uAng;
  86472. rtt.vAng = texture.vAng;
  86473. rtt.wAng = texture.wAng;
  86474. rtt.coordinatesIndex = texture.coordinatesIndex;
  86475. rtt.level = texture.level;
  86476. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86477. rtt._texture.isReady = false;
  86478. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86479. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86480. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86481. passPostProcess.getEffect().executeWhenCompiled(function () {
  86482. passPostProcess.onApply = function (effect) {
  86483. effect.setTexture("textureSampler", texture);
  86484. };
  86485. var internalTexture = rtt.getInternalTexture();
  86486. if (internalTexture) {
  86487. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86488. engine.unBindFramebuffer(internalTexture);
  86489. rtt.disposeFramebufferObjects();
  86490. passPostProcess.dispose();
  86491. internalTexture.isReady = true;
  86492. }
  86493. });
  86494. return rtt;
  86495. };
  86496. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86497. if (!scene._environmentBRDFTexture) {
  86498. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86499. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86500. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86501. scene._environmentBRDFTexture = texture;
  86502. }
  86503. return scene._environmentBRDFTexture;
  86504. };
  86505. 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=";
  86506. return TextureTools;
  86507. }());
  86508. BABYLON.TextureTools = TextureTools;
  86509. })(BABYLON || (BABYLON = {}));
  86510. //# sourceMappingURL=babylon.textureTools.js.map
  86511. var BABYLON;
  86512. (function (BABYLON) {
  86513. var FramingBehavior = /** @class */ (function () {
  86514. function FramingBehavior() {
  86515. this._mode = FramingBehavior.FitFrustumSidesMode;
  86516. this._radiusScale = 1.0;
  86517. this._positionScale = 0.5;
  86518. this._defaultElevation = 0.3;
  86519. this._elevationReturnTime = 1500;
  86520. this._elevationReturnWaitTime = 1000;
  86521. this._zoomStopsAnimation = false;
  86522. this._framingTime = 1500;
  86523. this._isPointerDown = false;
  86524. this._lastInteractionTime = -Infinity;
  86525. // Framing control
  86526. this._animatables = new Array();
  86527. this._betaIsAnimating = false;
  86528. }
  86529. Object.defineProperty(FramingBehavior.prototype, "name", {
  86530. get: function () {
  86531. return "Framing";
  86532. },
  86533. enumerable: true,
  86534. configurable: true
  86535. });
  86536. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86537. /**
  86538. * Gets current mode used by the behavior.
  86539. */
  86540. get: function () {
  86541. return this._mode;
  86542. },
  86543. /**
  86544. * Sets the current mode used by the behavior
  86545. */
  86546. set: function (mode) {
  86547. this._mode = mode;
  86548. },
  86549. enumerable: true,
  86550. configurable: true
  86551. });
  86552. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86553. /**
  86554. * Gets the scale applied to the radius
  86555. */
  86556. get: function () {
  86557. return this._radiusScale;
  86558. },
  86559. /**
  86560. * Sets the scale applied to the radius (1 by default)
  86561. */
  86562. set: function (radius) {
  86563. this._radiusScale = radius;
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86569. /**
  86570. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86571. */
  86572. get: function () {
  86573. return this._positionScale;
  86574. },
  86575. /**
  86576. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86577. */
  86578. set: function (scale) {
  86579. this._positionScale = scale;
  86580. },
  86581. enumerable: true,
  86582. configurable: true
  86583. });
  86584. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86585. /**
  86586. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86587. * behaviour is triggered, in radians.
  86588. */
  86589. get: function () {
  86590. return this._defaultElevation;
  86591. },
  86592. /**
  86593. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86594. * behaviour is triggered, in radians.
  86595. */
  86596. set: function (elevation) {
  86597. this._defaultElevation = elevation;
  86598. },
  86599. enumerable: true,
  86600. configurable: true
  86601. });
  86602. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86603. /**
  86604. * Gets the time (in milliseconds) taken to return to the default beta position.
  86605. * Negative value indicates camera should not return to default.
  86606. */
  86607. get: function () {
  86608. return this._elevationReturnTime;
  86609. },
  86610. /**
  86611. * Sets the time (in milliseconds) taken to return to the default beta position.
  86612. * Negative value indicates camera should not return to default.
  86613. */
  86614. set: function (speed) {
  86615. this._elevationReturnTime = speed;
  86616. },
  86617. enumerable: true,
  86618. configurable: true
  86619. });
  86620. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86621. /**
  86622. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86623. */
  86624. get: function () {
  86625. return this._elevationReturnWaitTime;
  86626. },
  86627. /**
  86628. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86629. */
  86630. set: function (time) {
  86631. this._elevationReturnWaitTime = time;
  86632. },
  86633. enumerable: true,
  86634. configurable: true
  86635. });
  86636. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86637. /**
  86638. * Gets the flag that indicates if user zooming should stop animation.
  86639. */
  86640. get: function () {
  86641. return this._zoomStopsAnimation;
  86642. },
  86643. /**
  86644. * Sets the flag that indicates if user zooming should stop animation.
  86645. */
  86646. set: function (flag) {
  86647. this._zoomStopsAnimation = flag;
  86648. },
  86649. enumerable: true,
  86650. configurable: true
  86651. });
  86652. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86653. /**
  86654. * Gets the transition time when framing the mesh, in milliseconds
  86655. */
  86656. get: function () {
  86657. return this._framingTime;
  86658. },
  86659. /**
  86660. * Sets the transition time when framing the mesh, in milliseconds
  86661. */
  86662. set: function (time) {
  86663. this._framingTime = time;
  86664. },
  86665. enumerable: true,
  86666. configurable: true
  86667. });
  86668. FramingBehavior.prototype.init = function () {
  86669. // Do notihng
  86670. };
  86671. FramingBehavior.prototype.attach = function (camera) {
  86672. var _this = this;
  86673. this._attachedCamera = camera;
  86674. var scene = this._attachedCamera.getScene();
  86675. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86676. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86677. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86678. _this._isPointerDown = true;
  86679. return;
  86680. }
  86681. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86682. _this._isPointerDown = false;
  86683. }
  86684. });
  86685. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86686. if (mesh) {
  86687. _this.zoomOnMesh(mesh);
  86688. }
  86689. });
  86690. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86691. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86692. _this._applyUserInteraction();
  86693. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86694. // back to the default position after a given timeout
  86695. _this._maintainCameraAboveGround();
  86696. });
  86697. };
  86698. FramingBehavior.prototype.detach = function () {
  86699. if (!this._attachedCamera) {
  86700. return;
  86701. }
  86702. var scene = this._attachedCamera.getScene();
  86703. if (this._onPrePointerObservableObserver) {
  86704. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86705. }
  86706. if (this._onAfterCheckInputsObserver) {
  86707. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86708. }
  86709. if (this._onMeshTargetChangedObserver) {
  86710. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86711. }
  86712. this._attachedCamera = null;
  86713. };
  86714. /**
  86715. * Targets the given mesh and updates zoom level accordingly.
  86716. * @param mesh The mesh to target.
  86717. * @param radius Optional. If a cached radius position already exists, overrides default.
  86718. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86719. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86720. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86721. */
  86722. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86723. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86724. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86725. mesh.computeWorldMatrix(true);
  86726. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86727. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86728. };
  86729. /**
  86730. * Targets the given mesh with its children and updates zoom level accordingly.
  86731. * @param mesh The mesh to target.
  86732. * @param radius Optional. If a cached radius position already exists, overrides default.
  86733. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86734. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86735. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86736. */
  86737. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86738. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86739. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86740. mesh.computeWorldMatrix(true);
  86741. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86742. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86743. };
  86744. /**
  86745. * Targets the given meshes with their children and updates zoom level accordingly.
  86746. * @param meshes The mesh to target.
  86747. * @param radius Optional. If a cached radius position already exists, overrides default.
  86748. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86749. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86750. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86751. */
  86752. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86753. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86754. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86755. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86756. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86757. for (var i = 0; i < meshes.length; i++) {
  86758. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86759. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86760. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86761. }
  86762. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86763. };
  86764. /**
  86765. * Targets the given mesh and updates zoom level accordingly.
  86766. * @param mesh The mesh to target.
  86767. * @param radius Optional. If a cached radius position already exists, overrides default.
  86768. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86769. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86770. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86771. */
  86772. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86773. var _this = this;
  86774. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86775. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86776. var zoomTarget;
  86777. if (!this._attachedCamera) {
  86778. return;
  86779. }
  86780. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86781. var bottom = minimumWorld.y;
  86782. var top = maximumWorld.y;
  86783. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86784. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86785. if (focusOnOriginXZ) {
  86786. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86787. }
  86788. else {
  86789. var centerWorld = minimumWorld.add(radiusWorld);
  86790. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86791. }
  86792. if (!this._vectorTransition) {
  86793. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86794. }
  86795. this._betaIsAnimating = true;
  86796. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86797. if (animatable) {
  86798. this._animatables.push(animatable);
  86799. }
  86800. // sets the radius and lower radius bounds
  86801. // Small delta ensures camera is not always at lower zoom limit.
  86802. var radius = 0;
  86803. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86804. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86805. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86806. radius = position;
  86807. }
  86808. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86809. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86810. if (this._attachedCamera.lowerRadiusLimit === null) {
  86811. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86812. }
  86813. }
  86814. // Set sensibilities
  86815. var extend = maximumWorld.subtract(minimumWorld).length();
  86816. this._attachedCamera.panningSensibility = 5000 / extend;
  86817. this._attachedCamera.wheelPrecision = 100 / radius;
  86818. // transition to new radius
  86819. if (!this._radiusTransition) {
  86820. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86821. }
  86822. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86823. if (onAnimationEnd) {
  86824. onAnimationEnd();
  86825. }
  86826. if (_this._attachedCamera) {
  86827. _this._attachedCamera.storeState();
  86828. }
  86829. });
  86830. if (animatable) {
  86831. this._animatables.push(animatable);
  86832. }
  86833. };
  86834. /**
  86835. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86836. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86837. * frustum width.
  86838. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86839. * to fully enclose the mesh in the viewing frustum.
  86840. */
  86841. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86842. var size = maximumWorld.subtract(minimumWorld);
  86843. var boxVectorGlobalDiagonal = size.length();
  86844. var frustumSlope = this._getFrustumSlope();
  86845. // Formula for setting distance
  86846. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86847. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86848. // Horizon distance
  86849. var radius = radiusWithoutFraming * this._radiusScale;
  86850. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86851. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86852. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86853. var camera = this._attachedCamera;
  86854. if (!camera) {
  86855. return 0;
  86856. }
  86857. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86858. // Don't exceed the requested limit
  86859. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86860. }
  86861. // Don't exceed the upper radius limit
  86862. if (camera.upperRadiusLimit) {
  86863. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86864. }
  86865. return distance;
  86866. };
  86867. /**
  86868. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86869. * is automatically returned to its default position (expected to be above ground plane).
  86870. */
  86871. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86872. var _this = this;
  86873. if (this._elevationReturnTime < 0) {
  86874. return;
  86875. }
  86876. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86877. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86878. var limitBeta = Math.PI * 0.5;
  86879. // Bring the camera back up if below the ground plane
  86880. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86881. this._betaIsAnimating = true;
  86882. //Transition to new position
  86883. this.stopAllAnimations();
  86884. if (!this._betaTransition) {
  86885. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86886. }
  86887. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86888. _this._clearAnimationLocks();
  86889. _this.stopAllAnimations();
  86890. });
  86891. if (animatabe) {
  86892. this._animatables.push(animatabe);
  86893. }
  86894. }
  86895. };
  86896. /**
  86897. * Returns the frustum slope based on the canvas ratio and camera FOV
  86898. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86899. */
  86900. FramingBehavior.prototype._getFrustumSlope = function () {
  86901. // Calculate the viewport ratio
  86902. // Aspect Ratio is Height/Width.
  86903. var camera = this._attachedCamera;
  86904. if (!camera) {
  86905. return BABYLON.Vector2.Zero();
  86906. }
  86907. var engine = camera.getScene().getEngine();
  86908. var aspectRatio = engine.getAspectRatio(camera);
  86909. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86910. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86911. var frustumSlopeY = Math.tan(camera.fov / 2);
  86912. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86913. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86914. // along the forward vector.
  86915. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86916. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86917. };
  86918. /**
  86919. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86920. */
  86921. FramingBehavior.prototype._clearAnimationLocks = function () {
  86922. this._betaIsAnimating = false;
  86923. };
  86924. /**
  86925. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86926. */
  86927. FramingBehavior.prototype._applyUserInteraction = function () {
  86928. if (this.isUserIsMoving) {
  86929. this._lastInteractionTime = BABYLON.Tools.Now;
  86930. this.stopAllAnimations();
  86931. this._clearAnimationLocks();
  86932. }
  86933. };
  86934. /**
  86935. * Stops and removes all animations that have been applied to the camera
  86936. */
  86937. FramingBehavior.prototype.stopAllAnimations = function () {
  86938. if (this._attachedCamera) {
  86939. this._attachedCamera.animations = [];
  86940. }
  86941. while (this._animatables.length) {
  86942. if (this._animatables[0]) {
  86943. this._animatables[0].onAnimationEnd = null;
  86944. this._animatables[0].stop();
  86945. }
  86946. this._animatables.shift();
  86947. }
  86948. };
  86949. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86950. /**
  86951. * Gets a value indicating if the user is moving the camera
  86952. */
  86953. get: function () {
  86954. if (!this._attachedCamera) {
  86955. return false;
  86956. }
  86957. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86958. this._attachedCamera.inertialBetaOffset !== 0 ||
  86959. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86960. this._attachedCamera.inertialPanningX !== 0 ||
  86961. this._attachedCamera.inertialPanningY !== 0 ||
  86962. this._isPointerDown;
  86963. },
  86964. enumerable: true,
  86965. configurable: true
  86966. });
  86967. /**
  86968. * The easing function used by animations
  86969. */
  86970. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86971. /**
  86972. * The easing mode used by animations
  86973. */
  86974. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86975. // Statics
  86976. /**
  86977. * The camera can move all the way towards the mesh.
  86978. */
  86979. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86980. /**
  86981. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86982. */
  86983. FramingBehavior.FitFrustumSidesMode = 1;
  86984. return FramingBehavior;
  86985. }());
  86986. BABYLON.FramingBehavior = FramingBehavior;
  86987. })(BABYLON || (BABYLON = {}));
  86988. //# sourceMappingURL=babylon.framingBehavior.js.map
  86989. var BABYLON;
  86990. (function (BABYLON) {
  86991. /**
  86992. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86993. */
  86994. var BouncingBehavior = /** @class */ (function () {
  86995. function BouncingBehavior() {
  86996. /**
  86997. * The duration of the animation, in milliseconds
  86998. */
  86999. this.transitionDuration = 450;
  87000. /**
  87001. * Length of the distance animated by the transition when lower radius is reached
  87002. */
  87003. this.lowerRadiusTransitionRange = 2;
  87004. /**
  87005. * Length of the distance animated by the transition when upper radius is reached
  87006. */
  87007. this.upperRadiusTransitionRange = -2;
  87008. this._autoTransitionRange = false;
  87009. // Animations
  87010. this._radiusIsAnimating = false;
  87011. this._radiusBounceTransition = null;
  87012. this._animatables = new Array();
  87013. }
  87014. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87015. get: function () {
  87016. return "Bouncing";
  87017. },
  87018. enumerable: true,
  87019. configurable: true
  87020. });
  87021. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87022. /**
  87023. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87024. */
  87025. get: function () {
  87026. return this._autoTransitionRange;
  87027. },
  87028. /**
  87029. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87030. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87031. */
  87032. set: function (value) {
  87033. var _this = this;
  87034. if (this._autoTransitionRange === value) {
  87035. return;
  87036. }
  87037. this._autoTransitionRange = value;
  87038. var camera = this._attachedCamera;
  87039. if (!camera) {
  87040. return;
  87041. }
  87042. if (value) {
  87043. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87044. if (!mesh) {
  87045. return;
  87046. }
  87047. mesh.computeWorldMatrix(true);
  87048. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87049. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87050. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87051. });
  87052. }
  87053. else if (this._onMeshTargetChangedObserver) {
  87054. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87055. }
  87056. },
  87057. enumerable: true,
  87058. configurable: true
  87059. });
  87060. BouncingBehavior.prototype.init = function () {
  87061. // Do notihng
  87062. };
  87063. BouncingBehavior.prototype.attach = function (camera) {
  87064. var _this = this;
  87065. this._attachedCamera = camera;
  87066. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87067. if (!_this._attachedCamera) {
  87068. return;
  87069. }
  87070. // Add the bounce animation to the lower radius limit
  87071. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87072. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87073. }
  87074. // Add the bounce animation to the upper radius limit
  87075. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87076. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87077. }
  87078. });
  87079. };
  87080. BouncingBehavior.prototype.detach = function () {
  87081. if (!this._attachedCamera) {
  87082. return;
  87083. }
  87084. if (this._onAfterCheckInputsObserver) {
  87085. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87086. }
  87087. if (this._onMeshTargetChangedObserver) {
  87088. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87089. }
  87090. this._attachedCamera = null;
  87091. };
  87092. /**
  87093. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87094. * @param radiusLimit The limit to check against.
  87095. * @return Bool to indicate if at limit.
  87096. */
  87097. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87098. if (!this._attachedCamera) {
  87099. return false;
  87100. }
  87101. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87102. return true;
  87103. }
  87104. return false;
  87105. };
  87106. /**
  87107. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87108. * @param radiusDelta The delta by which to animate to. Can be negative.
  87109. */
  87110. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87111. var _this = this;
  87112. if (!this._attachedCamera) {
  87113. return;
  87114. }
  87115. if (!this._radiusBounceTransition) {
  87116. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87117. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87118. }
  87119. // Prevent zoom until bounce has completed
  87120. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87121. this._attachedCamera.wheelPrecision = Infinity;
  87122. this._attachedCamera.inertialRadiusOffset = 0;
  87123. // Animate to the radius limit
  87124. this.stopAllAnimations();
  87125. this._radiusIsAnimating = true;
  87126. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87127. if (animatable) {
  87128. this._animatables.push(animatable);
  87129. }
  87130. };
  87131. /**
  87132. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87133. */
  87134. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87135. this._radiusIsAnimating = false;
  87136. if (this._attachedCamera) {
  87137. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87138. }
  87139. };
  87140. /**
  87141. * Stops and removes all animations that have been applied to the camera
  87142. */
  87143. BouncingBehavior.prototype.stopAllAnimations = function () {
  87144. if (this._attachedCamera) {
  87145. this._attachedCamera.animations = [];
  87146. }
  87147. while (this._animatables.length) {
  87148. this._animatables[0].onAnimationEnd = null;
  87149. this._animatables[0].stop();
  87150. this._animatables.shift();
  87151. }
  87152. };
  87153. /**
  87154. * The easing function used by animations
  87155. */
  87156. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87157. /**
  87158. * The easing mode used by animations
  87159. */
  87160. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87161. return BouncingBehavior;
  87162. }());
  87163. BABYLON.BouncingBehavior = BouncingBehavior;
  87164. })(BABYLON || (BABYLON = {}));
  87165. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87166. var BABYLON;
  87167. (function (BABYLON) {
  87168. var AutoRotationBehavior = /** @class */ (function () {
  87169. function AutoRotationBehavior() {
  87170. this._zoomStopsAnimation = false;
  87171. this._idleRotationSpeed = 0.05;
  87172. this._idleRotationWaitTime = 2000;
  87173. this._idleRotationSpinupTime = 2000;
  87174. this._isPointerDown = false;
  87175. this._lastFrameTime = null;
  87176. this._lastInteractionTime = -Infinity;
  87177. this._cameraRotationSpeed = 0;
  87178. this._lastFrameRadius = 0;
  87179. }
  87180. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87181. get: function () {
  87182. return "AutoRotation";
  87183. },
  87184. enumerable: true,
  87185. configurable: true
  87186. });
  87187. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87188. /**
  87189. * Gets the flag that indicates if user zooming should stop animation.
  87190. */
  87191. get: function () {
  87192. return this._zoomStopsAnimation;
  87193. },
  87194. /**
  87195. * Sets the flag that indicates if user zooming should stop animation.
  87196. */
  87197. set: function (flag) {
  87198. this._zoomStopsAnimation = flag;
  87199. },
  87200. enumerable: true,
  87201. configurable: true
  87202. });
  87203. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87204. /**
  87205. * Gets the default speed at which the camera rotates around the model.
  87206. */
  87207. get: function () {
  87208. return this._idleRotationSpeed;
  87209. },
  87210. /**
  87211. * Sets the default speed at which the camera rotates around the model.
  87212. */
  87213. set: function (speed) {
  87214. this._idleRotationSpeed = speed;
  87215. },
  87216. enumerable: true,
  87217. configurable: true
  87218. });
  87219. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87220. /**
  87221. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87222. */
  87223. get: function () {
  87224. return this._idleRotationWaitTime;
  87225. },
  87226. /**
  87227. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87228. */
  87229. set: function (time) {
  87230. this._idleRotationWaitTime = time;
  87231. },
  87232. enumerable: true,
  87233. configurable: true
  87234. });
  87235. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87236. /**
  87237. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87238. */
  87239. get: function () {
  87240. return this._idleRotationSpinupTime;
  87241. },
  87242. /**
  87243. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87244. */
  87245. set: function (time) {
  87246. this._idleRotationSpinupTime = time;
  87247. },
  87248. enumerable: true,
  87249. configurable: true
  87250. });
  87251. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87252. /**
  87253. * Gets a value indicating if the camera is currently rotating because of this behavior
  87254. */
  87255. get: function () {
  87256. return Math.abs(this._cameraRotationSpeed) > 0;
  87257. },
  87258. enumerable: true,
  87259. configurable: true
  87260. });
  87261. AutoRotationBehavior.prototype.init = function () {
  87262. // Do notihng
  87263. };
  87264. AutoRotationBehavior.prototype.attach = function (camera) {
  87265. var _this = this;
  87266. this._attachedCamera = camera;
  87267. var scene = this._attachedCamera.getScene();
  87268. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87269. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87270. _this._isPointerDown = true;
  87271. return;
  87272. }
  87273. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87274. _this._isPointerDown = false;
  87275. }
  87276. });
  87277. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87278. var now = BABYLON.Tools.Now;
  87279. var dt = 0;
  87280. if (_this._lastFrameTime != null) {
  87281. dt = now - _this._lastFrameTime;
  87282. }
  87283. _this._lastFrameTime = now;
  87284. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87285. _this._applyUserInteraction();
  87286. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87287. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87288. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87289. // Step camera rotation by rotation speed
  87290. if (_this._attachedCamera) {
  87291. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87292. }
  87293. });
  87294. };
  87295. AutoRotationBehavior.prototype.detach = function () {
  87296. if (!this._attachedCamera) {
  87297. return;
  87298. }
  87299. var scene = this._attachedCamera.getScene();
  87300. if (this._onPrePointerObservableObserver) {
  87301. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87302. }
  87303. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87304. this._attachedCamera = null;
  87305. };
  87306. /**
  87307. * Returns true if user is scrolling.
  87308. * @return true if user is scrolling.
  87309. */
  87310. AutoRotationBehavior.prototype._userIsZooming = function () {
  87311. if (!this._attachedCamera) {
  87312. return false;
  87313. }
  87314. return this._attachedCamera.inertialRadiusOffset !== 0;
  87315. };
  87316. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87317. if (!this._attachedCamera) {
  87318. return false;
  87319. }
  87320. var zoomHasHitLimit = false;
  87321. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87322. zoomHasHitLimit = true;
  87323. }
  87324. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87325. this._lastFrameRadius = this._attachedCamera.radius;
  87326. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87327. };
  87328. /**
  87329. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87330. */
  87331. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87332. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87333. this._lastInteractionTime = BABYLON.Tools.Now;
  87334. }
  87335. };
  87336. // Tools
  87337. AutoRotationBehavior.prototype._userIsMoving = function () {
  87338. if (!this._attachedCamera) {
  87339. return false;
  87340. }
  87341. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87342. this._attachedCamera.inertialBetaOffset !== 0 ||
  87343. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87344. this._attachedCamera.inertialPanningX !== 0 ||
  87345. this._attachedCamera.inertialPanningY !== 0 ||
  87346. this._isPointerDown;
  87347. };
  87348. return AutoRotationBehavior;
  87349. }());
  87350. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87351. })(BABYLON || (BABYLON = {}));
  87352. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87353. var BABYLON;
  87354. (function (BABYLON) {
  87355. /**
  87356. * This class can be used to get instrumentation data from a Babylon engine
  87357. */
  87358. var EngineInstrumentation = /** @class */ (function () {
  87359. function EngineInstrumentation(engine) {
  87360. this.engine = engine;
  87361. this._captureGPUFrameTime = false;
  87362. this._gpuFrameTime = new BABYLON.PerfCounter();
  87363. this._captureShaderCompilationTime = false;
  87364. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87365. // Observers
  87366. this._onBeginFrameObserver = null;
  87367. this._onEndFrameObserver = null;
  87368. this._onBeforeShaderCompilationObserver = null;
  87369. this._onAfterShaderCompilationObserver = null;
  87370. }
  87371. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87372. // Properties
  87373. /**
  87374. * Gets the perf counter used for GPU frame time
  87375. */
  87376. get: function () {
  87377. return this._gpuFrameTime;
  87378. },
  87379. enumerable: true,
  87380. configurable: true
  87381. });
  87382. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87383. /**
  87384. * Gets the GPU frame time capture status
  87385. */
  87386. get: function () {
  87387. return this._captureGPUFrameTime;
  87388. },
  87389. /**
  87390. * Enable or disable the GPU frame time capture
  87391. */
  87392. set: function (value) {
  87393. var _this = this;
  87394. if (value === this._captureGPUFrameTime) {
  87395. return;
  87396. }
  87397. this._captureGPUFrameTime = value;
  87398. if (value) {
  87399. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87400. if (!_this._gpuFrameTimeToken) {
  87401. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87402. }
  87403. });
  87404. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87405. if (!_this._gpuFrameTimeToken) {
  87406. return;
  87407. }
  87408. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87409. if (time > -1) {
  87410. _this._gpuFrameTimeToken = null;
  87411. _this._gpuFrameTime.fetchNewFrame();
  87412. _this._gpuFrameTime.addCount(time, true);
  87413. }
  87414. });
  87415. }
  87416. else {
  87417. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87418. this._onBeginFrameObserver = null;
  87419. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87420. this._onEndFrameObserver = null;
  87421. }
  87422. },
  87423. enumerable: true,
  87424. configurable: true
  87425. });
  87426. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87427. /**
  87428. * Gets the perf counter used for shader compilation time
  87429. */
  87430. get: function () {
  87431. return this._shaderCompilationTime;
  87432. },
  87433. enumerable: true,
  87434. configurable: true
  87435. });
  87436. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87437. /**
  87438. * Gets the shader compilation time capture status
  87439. */
  87440. get: function () {
  87441. return this._captureShaderCompilationTime;
  87442. },
  87443. /**
  87444. * Enable or disable the shader compilation time capture
  87445. */
  87446. set: function (value) {
  87447. var _this = this;
  87448. if (value === this._captureShaderCompilationTime) {
  87449. return;
  87450. }
  87451. this._captureShaderCompilationTime = value;
  87452. if (value) {
  87453. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87454. _this._shaderCompilationTime.fetchNewFrame();
  87455. _this._shaderCompilationTime.beginMonitoring();
  87456. });
  87457. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87458. _this._shaderCompilationTime.endMonitoring();
  87459. });
  87460. }
  87461. else {
  87462. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87463. this._onBeforeShaderCompilationObserver = null;
  87464. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87465. this._onAfterShaderCompilationObserver = null;
  87466. }
  87467. },
  87468. enumerable: true,
  87469. configurable: true
  87470. });
  87471. EngineInstrumentation.prototype.dispose = function () {
  87472. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87473. this._onBeginFrameObserver = null;
  87474. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87475. this._onEndFrameObserver = null;
  87476. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87477. this._onBeforeShaderCompilationObserver = null;
  87478. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87479. this._onAfterShaderCompilationObserver = null;
  87480. this.engine = null;
  87481. };
  87482. return EngineInstrumentation;
  87483. }());
  87484. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87485. })(BABYLON || (BABYLON = {}));
  87486. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87487. var BABYLON;
  87488. (function (BABYLON) {
  87489. /**
  87490. * This class can be used to get instrumentation data from a Babylon engine
  87491. */
  87492. var SceneInstrumentation = /** @class */ (function () {
  87493. function SceneInstrumentation(scene) {
  87494. var _this = this;
  87495. this.scene = scene;
  87496. this._captureActiveMeshesEvaluationTime = false;
  87497. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87498. this._captureRenderTargetsRenderTime = false;
  87499. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87500. this._captureFrameTime = false;
  87501. this._frameTime = new BABYLON.PerfCounter();
  87502. this._captureRenderTime = false;
  87503. this._renderTime = new BABYLON.PerfCounter();
  87504. this._captureInterFrameTime = false;
  87505. this._interFrameTime = new BABYLON.PerfCounter();
  87506. this._captureParticlesRenderTime = false;
  87507. this._particlesRenderTime = new BABYLON.PerfCounter();
  87508. this._captureSpritesRenderTime = false;
  87509. this._spritesRenderTime = new BABYLON.PerfCounter();
  87510. this._capturePhysicsTime = false;
  87511. this._physicsTime = new BABYLON.PerfCounter();
  87512. this._captureAnimationsTime = false;
  87513. this._animationsTime = new BABYLON.PerfCounter();
  87514. // Observers
  87515. this._onBeforeActiveMeshesEvaluationObserver = null;
  87516. this._onAfterActiveMeshesEvaluationObserver = null;
  87517. this._onBeforeRenderTargetsRenderObserver = null;
  87518. this._onAfterRenderTargetsRenderObserver = null;
  87519. this._onAfterRenderObserver = null;
  87520. this._onBeforeDrawPhaseObserver = null;
  87521. this._onAfterDrawPhaseObserver = null;
  87522. this._onBeforeAnimationsObserver = null;
  87523. this._onBeforeParticlesRenderingObserver = null;
  87524. this._onAfterParticlesRenderingObserver = null;
  87525. this._onBeforeSpritesRenderingObserver = null;
  87526. this._onAfterSpritesRenderingObserver = null;
  87527. this._onBeforePhysicsObserver = null;
  87528. this._onAfterPhysicsObserver = null;
  87529. this._onAfterAnimationsObserver = null;
  87530. // Before render
  87531. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87532. if (_this._captureActiveMeshesEvaluationTime) {
  87533. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87534. }
  87535. if (_this._captureRenderTargetsRenderTime) {
  87536. _this._renderTargetsRenderTime.fetchNewFrame();
  87537. }
  87538. if (_this._captureFrameTime) {
  87539. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87540. _this._frameTime.beginMonitoring();
  87541. }
  87542. if (_this._captureInterFrameTime) {
  87543. _this._interFrameTime.endMonitoring();
  87544. }
  87545. if (_this._captureParticlesRenderTime) {
  87546. _this._particlesRenderTime.fetchNewFrame();
  87547. }
  87548. if (_this._captureSpritesRenderTime) {
  87549. _this._spritesRenderTime.fetchNewFrame();
  87550. }
  87551. if (_this._captureAnimationsTime) {
  87552. _this._animationsTime.beginMonitoring();
  87553. }
  87554. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87555. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87556. });
  87557. // After render
  87558. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87559. if (_this._captureFrameTime) {
  87560. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87561. _this._frameTime.endMonitoring();
  87562. }
  87563. if (_this._captureRenderTime) {
  87564. _this._renderTime.endMonitoring(false);
  87565. }
  87566. if (_this._captureInterFrameTime) {
  87567. _this._interFrameTime.beginMonitoring();
  87568. }
  87569. });
  87570. }
  87571. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87572. // Properties
  87573. /**
  87574. * Gets the perf counter used for active meshes evaluation time
  87575. */
  87576. get: function () {
  87577. return this._activeMeshesEvaluationTime;
  87578. },
  87579. enumerable: true,
  87580. configurable: true
  87581. });
  87582. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87583. /**
  87584. * Gets the active meshes evaluation time capture status
  87585. */
  87586. get: function () {
  87587. return this._captureActiveMeshesEvaluationTime;
  87588. },
  87589. /**
  87590. * Enable or disable the active meshes evaluation time capture
  87591. */
  87592. set: function (value) {
  87593. var _this = this;
  87594. if (value === this._captureActiveMeshesEvaluationTime) {
  87595. return;
  87596. }
  87597. this._captureActiveMeshesEvaluationTime = value;
  87598. if (value) {
  87599. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87600. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87601. _this._activeMeshesEvaluationTime.beginMonitoring();
  87602. });
  87603. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87604. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87605. _this._activeMeshesEvaluationTime.endMonitoring();
  87606. });
  87607. }
  87608. else {
  87609. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87610. this._onBeforeActiveMeshesEvaluationObserver = null;
  87611. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87612. this._onAfterActiveMeshesEvaluationObserver = null;
  87613. }
  87614. },
  87615. enumerable: true,
  87616. configurable: true
  87617. });
  87618. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87619. /**
  87620. * Gets the perf counter used for render targets render time
  87621. */
  87622. get: function () {
  87623. return this._renderTargetsRenderTime;
  87624. },
  87625. enumerable: true,
  87626. configurable: true
  87627. });
  87628. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87629. /**
  87630. * Gets the render targets render time capture status
  87631. */
  87632. get: function () {
  87633. return this._captureRenderTargetsRenderTime;
  87634. },
  87635. /**
  87636. * Enable or disable the render targets render time capture
  87637. */
  87638. set: function (value) {
  87639. var _this = this;
  87640. if (value === this._captureRenderTargetsRenderTime) {
  87641. return;
  87642. }
  87643. this._captureRenderTargetsRenderTime = value;
  87644. if (value) {
  87645. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87646. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87647. _this._renderTargetsRenderTime.beginMonitoring();
  87648. });
  87649. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87650. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87651. _this._renderTargetsRenderTime.endMonitoring(false);
  87652. });
  87653. }
  87654. else {
  87655. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87656. this._onBeforeRenderTargetsRenderObserver = null;
  87657. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87658. this._onAfterRenderTargetsRenderObserver = null;
  87659. }
  87660. },
  87661. enumerable: true,
  87662. configurable: true
  87663. });
  87664. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87665. /**
  87666. * Gets the perf counter used for particles render time
  87667. */
  87668. get: function () {
  87669. return this._particlesRenderTime;
  87670. },
  87671. enumerable: true,
  87672. configurable: true
  87673. });
  87674. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87675. /**
  87676. * Gets the particles render time capture status
  87677. */
  87678. get: function () {
  87679. return this._captureParticlesRenderTime;
  87680. },
  87681. /**
  87682. * Enable or disable the particles render time capture
  87683. */
  87684. set: function (value) {
  87685. var _this = this;
  87686. if (value === this._captureParticlesRenderTime) {
  87687. return;
  87688. }
  87689. this._captureParticlesRenderTime = value;
  87690. if (value) {
  87691. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87692. BABYLON.Tools.StartPerformanceCounter("Particles");
  87693. _this._particlesRenderTime.beginMonitoring();
  87694. });
  87695. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87696. BABYLON.Tools.EndPerformanceCounter("Particles");
  87697. _this._particlesRenderTime.endMonitoring(false);
  87698. });
  87699. }
  87700. else {
  87701. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87702. this._onBeforeParticlesRenderingObserver = null;
  87703. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87704. this._onAfterParticlesRenderingObserver = null;
  87705. }
  87706. },
  87707. enumerable: true,
  87708. configurable: true
  87709. });
  87710. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87711. /**
  87712. * Gets the perf counter used for sprites render time
  87713. */
  87714. get: function () {
  87715. return this._spritesRenderTime;
  87716. },
  87717. enumerable: true,
  87718. configurable: true
  87719. });
  87720. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87721. /**
  87722. * Gets the sprites render time capture status
  87723. */
  87724. get: function () {
  87725. return this._captureSpritesRenderTime;
  87726. },
  87727. /**
  87728. * Enable or disable the sprites render time capture
  87729. */
  87730. set: function (value) {
  87731. var _this = this;
  87732. if (value === this._captureSpritesRenderTime) {
  87733. return;
  87734. }
  87735. this._captureSpritesRenderTime = value;
  87736. if (value) {
  87737. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87738. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87739. _this._spritesRenderTime.beginMonitoring();
  87740. });
  87741. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87742. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87743. _this._spritesRenderTime.endMonitoring(false);
  87744. });
  87745. }
  87746. else {
  87747. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87748. this._onBeforeSpritesRenderingObserver = null;
  87749. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87750. this._onAfterSpritesRenderingObserver = null;
  87751. }
  87752. },
  87753. enumerable: true,
  87754. configurable: true
  87755. });
  87756. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87757. /**
  87758. * Gets the perf counter used for physics time
  87759. */
  87760. get: function () {
  87761. return this._physicsTime;
  87762. },
  87763. enumerable: true,
  87764. configurable: true
  87765. });
  87766. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87767. /**
  87768. * Gets the physics time capture status
  87769. */
  87770. get: function () {
  87771. return this._capturePhysicsTime;
  87772. },
  87773. /**
  87774. * Enable or disable the physics time capture
  87775. */
  87776. set: function (value) {
  87777. var _this = this;
  87778. if (value === this._capturePhysicsTime) {
  87779. return;
  87780. }
  87781. this._capturePhysicsTime = value;
  87782. if (value) {
  87783. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87784. BABYLON.Tools.StartPerformanceCounter("Physics");
  87785. _this._physicsTime.beginMonitoring();
  87786. });
  87787. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87788. BABYLON.Tools.EndPerformanceCounter("Physics");
  87789. _this._physicsTime.endMonitoring();
  87790. });
  87791. }
  87792. else {
  87793. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87794. this._onBeforePhysicsObserver = null;
  87795. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87796. this._onAfterPhysicsObserver = null;
  87797. }
  87798. },
  87799. enumerable: true,
  87800. configurable: true
  87801. });
  87802. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87803. /**
  87804. * Gets the perf counter used for animations time
  87805. */
  87806. get: function () {
  87807. return this._animationsTime;
  87808. },
  87809. enumerable: true,
  87810. configurable: true
  87811. });
  87812. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87813. /**
  87814. * Gets the animations time capture status
  87815. */
  87816. get: function () {
  87817. return this._captureAnimationsTime;
  87818. },
  87819. /**
  87820. * Enable or disable the animations time capture
  87821. */
  87822. set: function (value) {
  87823. var _this = this;
  87824. if (value === this._captureAnimationsTime) {
  87825. return;
  87826. }
  87827. this._captureAnimationsTime = value;
  87828. if (value) {
  87829. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87830. _this._animationsTime.endMonitoring();
  87831. });
  87832. }
  87833. else {
  87834. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87835. this._onAfterAnimationsObserver = null;
  87836. }
  87837. },
  87838. enumerable: true,
  87839. configurable: true
  87840. });
  87841. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87842. /**
  87843. * Gets the perf counter used for frame time capture
  87844. */
  87845. get: function () {
  87846. return this._frameTime;
  87847. },
  87848. enumerable: true,
  87849. configurable: true
  87850. });
  87851. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87852. /**
  87853. * Gets the frame time capture status
  87854. */
  87855. get: function () {
  87856. return this._captureFrameTime;
  87857. },
  87858. /**
  87859. * Enable or disable the frame time capture
  87860. */
  87861. set: function (value) {
  87862. this._captureFrameTime = value;
  87863. },
  87864. enumerable: true,
  87865. configurable: true
  87866. });
  87867. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87868. /**
  87869. * Gets the perf counter used for inter-frames time capture
  87870. */
  87871. get: function () {
  87872. return this._interFrameTime;
  87873. },
  87874. enumerable: true,
  87875. configurable: true
  87876. });
  87877. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87878. /**
  87879. * Gets the inter-frames time capture status
  87880. */
  87881. get: function () {
  87882. return this._captureInterFrameTime;
  87883. },
  87884. /**
  87885. * Enable or disable the inter-frames time capture
  87886. */
  87887. set: function (value) {
  87888. this._captureInterFrameTime = value;
  87889. },
  87890. enumerable: true,
  87891. configurable: true
  87892. });
  87893. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87894. /**
  87895. * Gets the perf counter used for render time capture
  87896. */
  87897. get: function () {
  87898. return this._renderTime;
  87899. },
  87900. enumerable: true,
  87901. configurable: true
  87902. });
  87903. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87904. /**
  87905. * Gets the render time capture status
  87906. */
  87907. get: function () {
  87908. return this._captureRenderTime;
  87909. },
  87910. /**
  87911. * Enable or disable the render time capture
  87912. */
  87913. set: function (value) {
  87914. var _this = this;
  87915. if (value === this._captureRenderTime) {
  87916. return;
  87917. }
  87918. this._captureRenderTime = value;
  87919. if (value) {
  87920. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87921. _this._renderTime.beginMonitoring();
  87922. BABYLON.Tools.StartPerformanceCounter("Main render");
  87923. });
  87924. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87925. _this._renderTime.endMonitoring(false);
  87926. BABYLON.Tools.EndPerformanceCounter("Main render");
  87927. });
  87928. }
  87929. else {
  87930. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87931. this._onBeforeDrawPhaseObserver = null;
  87932. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87933. this._onAfterDrawPhaseObserver = null;
  87934. }
  87935. },
  87936. enumerable: true,
  87937. configurable: true
  87938. });
  87939. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87940. /**
  87941. * Gets the perf counter used for draw calls
  87942. */
  87943. get: function () {
  87944. return this.scene.getEngine()._drawCalls;
  87945. },
  87946. enumerable: true,
  87947. configurable: true
  87948. });
  87949. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87950. /**
  87951. * Gets the perf counter used for texture collisions
  87952. */
  87953. get: function () {
  87954. return this.scene.getEngine()._textureCollisions;
  87955. },
  87956. enumerable: true,
  87957. configurable: true
  87958. });
  87959. SceneInstrumentation.prototype.dispose = function () {
  87960. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87961. this._onAfterRenderObserver = null;
  87962. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87963. this._onBeforeActiveMeshesEvaluationObserver = null;
  87964. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87965. this._onAfterActiveMeshesEvaluationObserver = null;
  87966. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87967. this._onBeforeRenderTargetsRenderObserver = null;
  87968. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87969. this._onAfterRenderTargetsRenderObserver = null;
  87970. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87971. this._onBeforeAnimationsObserver = null;
  87972. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87973. this._onBeforeParticlesRenderingObserver = null;
  87974. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87975. this._onAfterParticlesRenderingObserver = null;
  87976. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87977. this._onBeforeSpritesRenderingObserver = null;
  87978. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87979. this._onAfterSpritesRenderingObserver = null;
  87980. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87981. this._onBeforeDrawPhaseObserver = null;
  87982. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87983. this._onAfterDrawPhaseObserver = null;
  87984. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87985. this._onBeforePhysicsObserver = null;
  87986. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87987. this._onAfterPhysicsObserver = null;
  87988. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87989. this._onAfterAnimationsObserver = null;
  87990. this.scene = null;
  87991. };
  87992. return SceneInstrumentation;
  87993. }());
  87994. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87995. })(BABYLON || (BABYLON = {}));
  87996. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87997. var BABYLON;
  87998. (function (BABYLON) {
  87999. var _TimeToken = /** @class */ (function () {
  88000. function _TimeToken() {
  88001. this._timeElapsedQueryEnded = false;
  88002. }
  88003. return _TimeToken;
  88004. }());
  88005. BABYLON._TimeToken = _TimeToken;
  88006. })(BABYLON || (BABYLON = {}));
  88007. //# sourceMappingURL=babylon.timeToken.js.map
  88008. var BABYLON;
  88009. (function (BABYLON) {
  88010. /**
  88011. * Background material defines definition.
  88012. * @ignore Mainly internal Use
  88013. */
  88014. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88015. __extends(BackgroundMaterialDefines, _super);
  88016. /**
  88017. * Constructor of the defines.
  88018. */
  88019. function BackgroundMaterialDefines() {
  88020. var _this = _super.call(this) || this;
  88021. /**
  88022. * True if the diffuse texture is in use.
  88023. */
  88024. _this.DIFFUSE = false;
  88025. /**
  88026. * The direct UV channel to use.
  88027. */
  88028. _this.DIFFUSEDIRECTUV = 0;
  88029. /**
  88030. * True if the diffuse texture is in gamma space.
  88031. */
  88032. _this.GAMMADIFFUSE = false;
  88033. /**
  88034. * True if the diffuse texture has opacity in the alpha channel.
  88035. */
  88036. _this.DIFFUSEHASALPHA = false;
  88037. /**
  88038. * True if you want the material to fade to transparent at grazing angle.
  88039. */
  88040. _this.OPACITYFRESNEL = false;
  88041. /**
  88042. * True if an extra blur needs to be added in the reflection.
  88043. */
  88044. _this.REFLECTIONBLUR = false;
  88045. /**
  88046. * True if you want the material to fade to reflection at grazing angle.
  88047. */
  88048. _this.REFLECTIONFRESNEL = false;
  88049. /**
  88050. * True if you want the material to falloff as far as you move away from the scene center.
  88051. */
  88052. _this.REFLECTIONFALLOFF = false;
  88053. /**
  88054. * False if the current Webgl implementation does not support the texture lod extension.
  88055. */
  88056. _this.TEXTURELODSUPPORT = false;
  88057. /**
  88058. * True to ensure the data are premultiplied.
  88059. */
  88060. _this.PREMULTIPLYALPHA = false;
  88061. /**
  88062. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88063. */
  88064. _this.USERGBCOLOR = false;
  88065. /**
  88066. * True to add noise in order to reduce the banding effect.
  88067. */
  88068. _this.NOISE = false;
  88069. /**
  88070. * is the reflection texture in BGR color scheme?
  88071. * Mainly used to solve a bug in ios10 video tag
  88072. */
  88073. _this.REFLECTIONBGR = false;
  88074. _this.IMAGEPROCESSING = false;
  88075. _this.VIGNETTE = false;
  88076. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88077. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88078. _this.TONEMAPPING = false;
  88079. _this.CONTRAST = false;
  88080. _this.COLORCURVES = false;
  88081. _this.COLORGRADING = false;
  88082. _this.COLORGRADING3D = false;
  88083. _this.SAMPLER3DGREENDEPTH = false;
  88084. _this.SAMPLER3DBGRMAP = false;
  88085. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88086. _this.EXPOSURE = false;
  88087. _this.GRAIN = false;
  88088. // Reflection.
  88089. _this.REFLECTION = false;
  88090. _this.REFLECTIONMAP_3D = false;
  88091. _this.REFLECTIONMAP_SPHERICAL = false;
  88092. _this.REFLECTIONMAP_PLANAR = false;
  88093. _this.REFLECTIONMAP_CUBIC = false;
  88094. _this.REFLECTIONMAP_PROJECTION = false;
  88095. _this.REFLECTIONMAP_SKYBOX = false;
  88096. _this.REFLECTIONMAP_EXPLICIT = false;
  88097. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88098. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88099. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88100. _this.INVERTCUBICMAP = false;
  88101. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88102. _this.LODINREFLECTIONALPHA = false;
  88103. _this.GAMMAREFLECTION = false;
  88104. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88105. // Default BJS.
  88106. _this.MAINUV1 = false;
  88107. _this.MAINUV2 = false;
  88108. _this.UV1 = false;
  88109. _this.UV2 = false;
  88110. _this.CLIPPLANE = false;
  88111. _this.POINTSIZE = false;
  88112. _this.FOG = false;
  88113. _this.NORMAL = false;
  88114. _this.NUM_BONE_INFLUENCERS = 0;
  88115. _this.BonesPerMesh = 0;
  88116. _this.INSTANCES = false;
  88117. _this.SHADOWFLOAT = false;
  88118. _this.rebuild();
  88119. return _this;
  88120. }
  88121. return BackgroundMaterialDefines;
  88122. }(BABYLON.MaterialDefines));
  88123. /**
  88124. * Background material used to create an efficient environement around your scene.
  88125. */
  88126. var BackgroundMaterial = /** @class */ (function (_super) {
  88127. __extends(BackgroundMaterial, _super);
  88128. /**
  88129. * Instantiates a Background Material in the given scene
  88130. * @param name The friendly name of the material
  88131. * @param scene The scene to add the material to
  88132. */
  88133. function BackgroundMaterial(name, scene) {
  88134. var _this = _super.call(this, name, scene) || this;
  88135. /**
  88136. * Key light Color (multiply against the R channel of the environement texture)
  88137. */
  88138. _this.primaryColor = BABYLON.Color3.White();
  88139. /**
  88140. * Key light Level (allowing HDR output of the background)
  88141. */
  88142. _this.primaryLevel = 1;
  88143. /**
  88144. * Secondary light Color (multiply against the G channel of the environement texture)
  88145. */
  88146. _this.secondaryColor = BABYLON.Color3.Gray();
  88147. /**
  88148. * Secondary light Level (allowing HDR output of the background)
  88149. */
  88150. _this.secondaryLevel = 1;
  88151. /**
  88152. * Tertiary light Color (multiply against the B channel of the environement texture)
  88153. */
  88154. _this.tertiaryColor = BABYLON.Color3.Black();
  88155. /**
  88156. * Tertiary light Level (allowing HDR output of the background)
  88157. */
  88158. _this.tertiaryLevel = 1;
  88159. /**
  88160. * Reflection Texture used in the material.
  88161. * Should be author in a specific way for the best result (refer to the documentation).
  88162. */
  88163. _this.reflectionTexture = null;
  88164. /**
  88165. * Reflection Texture level of blur.
  88166. *
  88167. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88168. * texture twice.
  88169. */
  88170. _this.reflectionBlur = 0;
  88171. /**
  88172. * Diffuse Texture used in the material.
  88173. * Should be author in a specific way for the best result (refer to the documentation).
  88174. */
  88175. _this.diffuseTexture = null;
  88176. _this._shadowLights = null;
  88177. /**
  88178. * Specify the list of lights casting shadow on the material.
  88179. * All scene shadow lights will be included if null.
  88180. */
  88181. _this.shadowLights = null;
  88182. /**
  88183. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88184. * soft lighting on the background.
  88185. */
  88186. _this.shadowBlurScale = 1;
  88187. /**
  88188. * Helps adjusting the shadow to a softer level if required.
  88189. * 0 means black shadows and 1 means no shadows.
  88190. */
  88191. _this.shadowLevel = 0;
  88192. /**
  88193. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88194. * It is usually zero but might be interesting to modify according to your setup.
  88195. */
  88196. _this.sceneCenter = BABYLON.Vector3.Zero();
  88197. /**
  88198. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88199. * This helps ensuring a nice transition when the camera goes under the ground.
  88200. */
  88201. _this.opacityFresnel = true;
  88202. /**
  88203. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88204. * This helps adding a mirror texture on the ground.
  88205. */
  88206. _this.reflectionFresnel = false;
  88207. /**
  88208. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88209. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88210. */
  88211. _this.reflectionFalloffDistance = 0.0;
  88212. /**
  88213. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88214. */
  88215. _this.reflectionAmount = 1.0;
  88216. /**
  88217. * This specifies the weight of the reflection at grazing angle.
  88218. */
  88219. _this.reflectionReflectance0 = 0.05;
  88220. /**
  88221. * This specifies the weight of the reflection at a perpendicular point of view.
  88222. */
  88223. _this.reflectionReflectance90 = 0.5;
  88224. /**
  88225. * Helps to directly use the maps channels instead of their level.
  88226. */
  88227. _this.useRGBColor = true;
  88228. /**
  88229. * This helps reducing the banding effect that could occur on the background.
  88230. */
  88231. _this.enableNoise = false;
  88232. _this._fovMultiplier = 1.0;
  88233. /**
  88234. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88235. * @type {boolean}
  88236. */
  88237. _this.useEquirectangularFOV = false;
  88238. _this._maxSimultaneousLights = 4;
  88239. /**
  88240. * Number of Simultaneous lights allowed on the material.
  88241. */
  88242. _this.maxSimultaneousLights = 4;
  88243. /**
  88244. * Keep track of the image processing observer to allow dispose and replace.
  88245. */
  88246. _this._imageProcessingObserver = null;
  88247. /**
  88248. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88249. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88250. */
  88251. _this.switchToBGR = false;
  88252. // Temp values kept as cache in the material.
  88253. _this._renderTargets = new BABYLON.SmartArray(16);
  88254. _this._reflectionControls = BABYLON.Vector4.Zero();
  88255. // Setup the default processing configuration to the scene.
  88256. _this._attachImageProcessingConfiguration(null);
  88257. _this.getRenderTargetTextures = function () {
  88258. _this._renderTargets.reset();
  88259. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88260. _this._renderTargets.push(_this._diffuseTexture);
  88261. }
  88262. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88263. _this._renderTargets.push(_this._reflectionTexture);
  88264. }
  88265. return _this._renderTargets;
  88266. };
  88267. return _this;
  88268. }
  88269. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88270. /**
  88271. * Sets the reflection reflectance fresnel values according to the default standard
  88272. * empirically know to work well :-)
  88273. */
  88274. set: function (value) {
  88275. var reflectionWeight = value;
  88276. if (reflectionWeight < 0.5) {
  88277. reflectionWeight = reflectionWeight * 2.0;
  88278. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88279. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88280. }
  88281. else {
  88282. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88283. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88284. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88285. }
  88286. },
  88287. enumerable: true,
  88288. configurable: true
  88289. });
  88290. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88291. /**
  88292. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88293. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88294. * Recommended to be keep at 1.0 except for special cases.
  88295. */
  88296. get: function () {
  88297. return this._fovMultiplier;
  88298. },
  88299. set: function (value) {
  88300. if (isNaN(value)) {
  88301. value = 1.0;
  88302. }
  88303. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88304. },
  88305. enumerable: true,
  88306. configurable: true
  88307. });
  88308. /**
  88309. * Attaches a new image processing configuration to the PBR Material.
  88310. * @param configuration (if null the scene configuration will be use)
  88311. */
  88312. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88313. var _this = this;
  88314. if (configuration === this._imageProcessingConfiguration) {
  88315. return;
  88316. }
  88317. // Detaches observer.
  88318. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88319. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88320. }
  88321. // Pick the scene configuration if needed.
  88322. if (!configuration) {
  88323. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88324. }
  88325. else {
  88326. this._imageProcessingConfiguration = configuration;
  88327. }
  88328. // Attaches observer.
  88329. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88330. _this._markAllSubMeshesAsImageProcessingDirty();
  88331. });
  88332. };
  88333. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88334. /**
  88335. * Gets the image processing configuration used either in this material.
  88336. */
  88337. get: function () {
  88338. return this._imageProcessingConfiguration;
  88339. },
  88340. /**
  88341. * Sets the Default image processing configuration used either in the this material.
  88342. *
  88343. * If sets to null, the scene one is in use.
  88344. */
  88345. set: function (value) {
  88346. this._attachImageProcessingConfiguration(value);
  88347. // Ensure the effect will be rebuilt.
  88348. this._markAllSubMeshesAsTexturesDirty();
  88349. },
  88350. enumerable: true,
  88351. configurable: true
  88352. });
  88353. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88354. /**
  88355. * Gets wether the color curves effect is enabled.
  88356. */
  88357. get: function () {
  88358. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88359. },
  88360. /**
  88361. * Sets wether the color curves effect is enabled.
  88362. */
  88363. set: function (value) {
  88364. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88365. },
  88366. enumerable: true,
  88367. configurable: true
  88368. });
  88369. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88370. /**
  88371. * Gets wether the color grading effect is enabled.
  88372. */
  88373. get: function () {
  88374. return this.imageProcessingConfiguration.colorGradingEnabled;
  88375. },
  88376. /**
  88377. * Gets wether the color grading effect is enabled.
  88378. */
  88379. set: function (value) {
  88380. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88381. },
  88382. enumerable: true,
  88383. configurable: true
  88384. });
  88385. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88386. /**
  88387. * Gets wether tonemapping is enabled or not.
  88388. */
  88389. get: function () {
  88390. return this._imageProcessingConfiguration.toneMappingEnabled;
  88391. },
  88392. /**
  88393. * Sets wether tonemapping is enabled or not
  88394. */
  88395. set: function (value) {
  88396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88397. },
  88398. enumerable: true,
  88399. configurable: true
  88400. });
  88401. ;
  88402. ;
  88403. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88404. /**
  88405. * The camera exposure used on this material.
  88406. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88407. * This corresponds to a photographic exposure.
  88408. */
  88409. get: function () {
  88410. return this._imageProcessingConfiguration.exposure;
  88411. },
  88412. /**
  88413. * The camera exposure used on this material.
  88414. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88415. * This corresponds to a photographic exposure.
  88416. */
  88417. set: function (value) {
  88418. this._imageProcessingConfiguration.exposure = value;
  88419. },
  88420. enumerable: true,
  88421. configurable: true
  88422. });
  88423. ;
  88424. ;
  88425. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88426. /**
  88427. * Gets The camera contrast used on this material.
  88428. */
  88429. get: function () {
  88430. return this._imageProcessingConfiguration.contrast;
  88431. },
  88432. /**
  88433. * Sets The camera contrast used on this material.
  88434. */
  88435. set: function (value) {
  88436. this._imageProcessingConfiguration.contrast = value;
  88437. },
  88438. enumerable: true,
  88439. configurable: true
  88440. });
  88441. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88442. /**
  88443. * Gets the Color Grading 2D Lookup Texture.
  88444. */
  88445. get: function () {
  88446. return this._imageProcessingConfiguration.colorGradingTexture;
  88447. },
  88448. /**
  88449. * Sets the Color Grading 2D Lookup Texture.
  88450. */
  88451. set: function (value) {
  88452. this.imageProcessingConfiguration.colorGradingTexture = value;
  88453. },
  88454. enumerable: true,
  88455. configurable: true
  88456. });
  88457. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88458. /**
  88459. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88460. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88461. * 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;
  88462. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88463. */
  88464. get: function () {
  88465. return this.imageProcessingConfiguration.colorCurves;
  88466. },
  88467. /**
  88468. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88469. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88470. * 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;
  88471. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88472. */
  88473. set: function (value) {
  88474. this.imageProcessingConfiguration.colorCurves = value;
  88475. },
  88476. enumerable: true,
  88477. configurable: true
  88478. });
  88479. /**
  88480. * The entire material has been created in order to prevent overdraw.
  88481. * @returns false
  88482. */
  88483. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88484. return true;
  88485. };
  88486. /**
  88487. * The entire material has been created in order to prevent overdraw.
  88488. * @returns true if blending is enable
  88489. */
  88490. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88491. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88492. };
  88493. /**
  88494. * Checks wether the material is ready to be rendered for a given mesh.
  88495. * @param mesh The mesh to render
  88496. * @param subMesh The submesh to check against
  88497. * @param useInstances Specify wether or not the material is used with instances
  88498. * @returns true if all the dependencies are ready (Textures, Effects...)
  88499. */
  88500. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88501. var _this = this;
  88502. if (useInstances === void 0) { useInstances = false; }
  88503. if (subMesh.effect && this.isFrozen) {
  88504. if (this._wasPreviouslyReady) {
  88505. return true;
  88506. }
  88507. }
  88508. if (!subMesh._materialDefines) {
  88509. subMesh._materialDefines = new BackgroundMaterialDefines();
  88510. }
  88511. var scene = this.getScene();
  88512. var defines = subMesh._materialDefines;
  88513. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88514. if (defines._renderId === scene.getRenderId()) {
  88515. return true;
  88516. }
  88517. }
  88518. var engine = scene.getEngine();
  88519. // Lights
  88520. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88521. defines._needNormals = true;
  88522. // Textures
  88523. if (defines._areTexturesDirty) {
  88524. defines._needUVs = false;
  88525. if (scene.texturesEnabled) {
  88526. if (scene.getEngine().getCaps().textureLOD) {
  88527. defines.TEXTURELODSUPPORT = true;
  88528. }
  88529. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88530. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88531. return false;
  88532. }
  88533. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88534. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88535. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88536. defines.OPACITYFRESNEL = this._opacityFresnel;
  88537. }
  88538. else {
  88539. defines.DIFFUSE = false;
  88540. defines.DIFFUSEHASALPHA = false;
  88541. defines.GAMMADIFFUSE = false;
  88542. defines.OPACITYFRESNEL = false;
  88543. }
  88544. var reflectionTexture = this._reflectionTexture;
  88545. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88546. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88547. return false;
  88548. }
  88549. defines.REFLECTION = true;
  88550. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88551. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88552. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88553. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88554. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88555. defines.REFLECTIONBGR = this.switchToBGR;
  88556. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88557. defines.INVERTCUBICMAP = true;
  88558. }
  88559. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88560. switch (reflectionTexture.coordinatesMode) {
  88561. case BABYLON.Texture.CUBIC_MODE:
  88562. case BABYLON.Texture.INVCUBIC_MODE:
  88563. defines.REFLECTIONMAP_CUBIC = true;
  88564. break;
  88565. case BABYLON.Texture.EXPLICIT_MODE:
  88566. defines.REFLECTIONMAP_EXPLICIT = true;
  88567. break;
  88568. case BABYLON.Texture.PLANAR_MODE:
  88569. defines.REFLECTIONMAP_PLANAR = true;
  88570. break;
  88571. case BABYLON.Texture.PROJECTION_MODE:
  88572. defines.REFLECTIONMAP_PROJECTION = true;
  88573. break;
  88574. case BABYLON.Texture.SKYBOX_MODE:
  88575. defines.REFLECTIONMAP_SKYBOX = true;
  88576. break;
  88577. case BABYLON.Texture.SPHERICAL_MODE:
  88578. defines.REFLECTIONMAP_SPHERICAL = true;
  88579. break;
  88580. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88581. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88582. break;
  88583. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88584. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88585. break;
  88586. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88587. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88588. break;
  88589. }
  88590. if (this.reflectionFresnel) {
  88591. defines.REFLECTIONFRESNEL = true;
  88592. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88593. this._reflectionControls.x = this.reflectionAmount;
  88594. this._reflectionControls.y = this.reflectionReflectance0;
  88595. this._reflectionControls.z = this.reflectionReflectance90;
  88596. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88597. }
  88598. else {
  88599. defines.REFLECTIONFRESNEL = false;
  88600. defines.REFLECTIONFALLOFF = false;
  88601. }
  88602. }
  88603. else {
  88604. defines.REFLECTION = false;
  88605. defines.REFLECTIONFALLOFF = false;
  88606. defines.REFLECTIONBLUR = false;
  88607. defines.REFLECTIONMAP_3D = false;
  88608. defines.REFLECTIONMAP_SPHERICAL = false;
  88609. defines.REFLECTIONMAP_PLANAR = false;
  88610. defines.REFLECTIONMAP_CUBIC = false;
  88611. defines.REFLECTIONMAP_PROJECTION = false;
  88612. defines.REFLECTIONMAP_SKYBOX = false;
  88613. defines.REFLECTIONMAP_EXPLICIT = false;
  88614. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88615. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88616. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88617. defines.INVERTCUBICMAP = false;
  88618. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88619. defines.LODINREFLECTIONALPHA = false;
  88620. defines.GAMMAREFLECTION = false;
  88621. }
  88622. }
  88623. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88624. defines.USERGBCOLOR = this._useRGBColor;
  88625. defines.NOISE = this._enableNoise;
  88626. }
  88627. if (defines._areImageProcessingDirty) {
  88628. if (!this._imageProcessingConfiguration.isReady()) {
  88629. return false;
  88630. }
  88631. this._imageProcessingConfiguration.prepareDefines(defines);
  88632. }
  88633. // Misc.
  88634. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88635. // Values that need to be evaluated on every frame
  88636. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88637. // Attribs
  88638. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88639. if (mesh) {
  88640. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88641. mesh.createNormals(true);
  88642. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88643. }
  88644. }
  88645. }
  88646. // Get correct effect
  88647. if (defines.isDirty) {
  88648. defines.markAsProcessed();
  88649. scene.resetCachedMaterial();
  88650. // Fallbacks
  88651. var fallbacks = new BABYLON.EffectFallbacks();
  88652. if (defines.FOG) {
  88653. fallbacks.addFallback(0, "FOG");
  88654. }
  88655. if (defines.POINTSIZE) {
  88656. fallbacks.addFallback(1, "POINTSIZE");
  88657. }
  88658. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88659. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88660. fallbacks.addCPUSkinningFallback(0, mesh);
  88661. }
  88662. //Attributes
  88663. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88664. if (defines.NORMAL) {
  88665. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88666. }
  88667. if (defines.UV1) {
  88668. attribs.push(BABYLON.VertexBuffer.UVKind);
  88669. }
  88670. if (defines.UV2) {
  88671. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88672. }
  88673. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88674. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88675. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88676. "vFogInfos", "vFogColor", "pointSize",
  88677. "vClipPlane", "mBones",
  88678. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88679. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88680. "shadowLevel", "alpha",
  88681. "vBackgroundCenter", "vReflectionControl",
  88682. "vDiffuseInfos", "diffuseMatrix",
  88683. ];
  88684. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88685. var uniformBuffers = ["Material", "Scene"];
  88686. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88687. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88688. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88689. uniformsNames: uniforms,
  88690. uniformBuffersNames: uniformBuffers,
  88691. samplers: samplers,
  88692. defines: defines,
  88693. maxSimultaneousLights: this._maxSimultaneousLights
  88694. });
  88695. var onCompiled = function (effect) {
  88696. if (_this.onCompiled) {
  88697. _this.onCompiled(effect);
  88698. }
  88699. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88700. };
  88701. var join = defines.toString();
  88702. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88703. attributes: attribs,
  88704. uniformsNames: uniforms,
  88705. uniformBuffersNames: uniformBuffers,
  88706. samplers: samplers,
  88707. defines: join,
  88708. fallbacks: fallbacks,
  88709. onCompiled: onCompiled,
  88710. onError: this.onError,
  88711. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88712. }, engine), defines);
  88713. this.buildUniformLayout();
  88714. }
  88715. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88716. return false;
  88717. }
  88718. defines._renderId = scene.getRenderId();
  88719. this._wasPreviouslyReady = true;
  88720. return true;
  88721. };
  88722. /**
  88723. * Build the uniform buffer used in the material.
  88724. */
  88725. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88726. // Order is important !
  88727. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88728. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88729. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88730. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88731. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88732. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88733. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88734. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88735. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88736. this._uniformBuffer.addUniform("pointSize", 1);
  88737. this._uniformBuffer.addUniform("shadowLevel", 1);
  88738. this._uniformBuffer.addUniform("alpha", 1);
  88739. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88740. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88741. this._uniformBuffer.create();
  88742. };
  88743. /**
  88744. * Unbind the material.
  88745. */
  88746. BackgroundMaterial.prototype.unbind = function () {
  88747. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88748. this._uniformBuffer.setTexture("diffuseSampler", null);
  88749. }
  88750. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88751. this._uniformBuffer.setTexture("reflectionSampler", null);
  88752. }
  88753. _super.prototype.unbind.call(this);
  88754. };
  88755. /**
  88756. * Bind only the world matrix to the material.
  88757. * @param world The world matrix to bind.
  88758. */
  88759. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88760. this._activeEffect.setMatrix("world", world);
  88761. };
  88762. /**
  88763. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88764. * @param world The world matrix to bind.
  88765. * @param subMesh The submesh to bind for.
  88766. */
  88767. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88768. var scene = this.getScene();
  88769. var defines = subMesh._materialDefines;
  88770. if (!defines) {
  88771. return;
  88772. }
  88773. var effect = subMesh.effect;
  88774. if (!effect) {
  88775. return;
  88776. }
  88777. this._activeEffect = effect;
  88778. // Matrices
  88779. this.bindOnlyWorldMatrix(world);
  88780. // Bones
  88781. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88782. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88783. if (mustRebind) {
  88784. this._uniformBuffer.bindToEffect(effect, "Material");
  88785. this.bindViewProjection(effect);
  88786. var reflectionTexture = this._reflectionTexture;
  88787. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88788. // Texture uniforms
  88789. if (scene.texturesEnabled) {
  88790. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88791. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88792. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88793. }
  88794. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88795. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88796. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88797. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88798. }
  88799. }
  88800. if (this.shadowLevel > 0) {
  88801. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88802. }
  88803. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88804. // Point size
  88805. if (this.pointsCloud) {
  88806. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88807. }
  88808. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88809. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88810. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88811. }
  88812. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88813. // Textures
  88814. if (scene.texturesEnabled) {
  88815. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88816. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88817. }
  88818. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88819. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88820. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88821. }
  88822. else if (!defines.REFLECTIONBLUR) {
  88823. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88824. }
  88825. else {
  88826. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88827. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88828. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88829. }
  88830. if (defines.REFLECTIONFRESNEL) {
  88831. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88832. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88833. }
  88834. }
  88835. }
  88836. // Clip plane
  88837. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88838. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88839. }
  88840. if (mustRebind || !this.isFrozen) {
  88841. if (scene.lightsEnabled) {
  88842. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88843. }
  88844. // View
  88845. this.bindView(effect);
  88846. // Fog
  88847. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88848. // image processing
  88849. this._imageProcessingConfiguration.bind(this._activeEffect);
  88850. }
  88851. this._uniformBuffer.update();
  88852. this._afterBind(mesh);
  88853. };
  88854. /**
  88855. * Dispose the material.
  88856. * @param forceDisposeEffect Force disposal of the associated effect.
  88857. * @param forceDisposeTextures Force disposal of the associated textures.
  88858. */
  88859. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88860. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88861. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88862. if (forceDisposeTextures) {
  88863. if (this.diffuseTexture) {
  88864. this.diffuseTexture.dispose();
  88865. }
  88866. if (this.reflectionTexture) {
  88867. this.reflectionTexture.dispose();
  88868. }
  88869. }
  88870. this._renderTargets.dispose();
  88871. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88872. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88873. }
  88874. _super.prototype.dispose.call(this, forceDisposeEffect);
  88875. };
  88876. /**
  88877. * Clones the material.
  88878. * @param name The cloned name.
  88879. * @returns The cloned material.
  88880. */
  88881. BackgroundMaterial.prototype.clone = function (name) {
  88882. var _this = this;
  88883. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88884. };
  88885. /**
  88886. * Serializes the current material to its JSON representation.
  88887. * @returns The JSON representation.
  88888. */
  88889. BackgroundMaterial.prototype.serialize = function () {
  88890. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88891. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88892. return serializationObject;
  88893. };
  88894. /**
  88895. * Gets the class name of the material
  88896. * @returns "BackgroundMaterial"
  88897. */
  88898. BackgroundMaterial.prototype.getClassName = function () {
  88899. return "BackgroundMaterial";
  88900. };
  88901. /**
  88902. * Parse a JSON input to create back a background material.
  88903. * @param source The JSON data to parse
  88904. * @param scene The scene to create the parsed material in
  88905. * @param rootUrl The root url of the assets the material depends upon
  88906. * @returns the instantiated BackgroundMaterial.
  88907. */
  88908. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88909. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88910. };
  88911. /**
  88912. * Standard reflectance value at parallel view angle.
  88913. */
  88914. BackgroundMaterial.StandardReflectance0 = 0.05;
  88915. /**
  88916. * Standard reflectance value at grazing angle.
  88917. */
  88918. BackgroundMaterial.StandardReflectance90 = 0.5;
  88919. __decorate([
  88920. BABYLON.serializeAsColor3()
  88921. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88922. __decorate([
  88923. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88924. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88925. __decorate([
  88926. BABYLON.serialize()
  88927. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88928. __decorate([
  88929. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88930. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88931. __decorate([
  88932. BABYLON.serializeAsColor3()
  88933. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88934. __decorate([
  88935. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88936. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88937. __decorate([
  88938. BABYLON.serialize()
  88939. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88940. __decorate([
  88941. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88942. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88943. __decorate([
  88944. BABYLON.serializeAsColor3()
  88945. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88946. __decorate([
  88947. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88948. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88949. __decorate([
  88950. BABYLON.serialize()
  88951. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88952. __decorate([
  88953. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88954. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88955. __decorate([
  88956. BABYLON.serializeAsTexture()
  88957. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88958. __decorate([
  88959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88960. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88961. __decorate([
  88962. BABYLON.serialize()
  88963. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88964. __decorate([
  88965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88966. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88967. __decorate([
  88968. BABYLON.serializeAsTexture()
  88969. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88970. __decorate([
  88971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88972. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88973. __decorate([
  88974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88975. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88976. __decorate([
  88977. BABYLON.serialize()
  88978. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88979. __decorate([
  88980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88981. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88982. __decorate([
  88983. BABYLON.serialize()
  88984. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88985. __decorate([
  88986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88987. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88988. __decorate([
  88989. BABYLON.serializeAsVector3()
  88990. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88991. __decorate([
  88992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88993. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88994. __decorate([
  88995. BABYLON.serialize()
  88996. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88997. __decorate([
  88998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88999. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89000. __decorate([
  89001. BABYLON.serialize()
  89002. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89003. __decorate([
  89004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89005. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89006. __decorate([
  89007. BABYLON.serialize()
  89008. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89009. __decorate([
  89010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89011. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89012. __decorate([
  89013. BABYLON.serialize()
  89014. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89015. __decorate([
  89016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89017. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89018. __decorate([
  89019. BABYLON.serialize()
  89020. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89021. __decorate([
  89022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89023. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89024. __decorate([
  89025. BABYLON.serialize()
  89026. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89027. __decorate([
  89028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89029. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89030. __decorate([
  89031. BABYLON.serialize()
  89032. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89033. __decorate([
  89034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89035. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89036. __decorate([
  89037. BABYLON.serialize()
  89038. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89039. __decorate([
  89040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89041. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89042. __decorate([
  89043. BABYLON.serialize()
  89044. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89045. __decorate([
  89046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89047. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89048. __decorate([
  89049. BABYLON.serializeAsImageProcessingConfiguration()
  89050. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89051. return BackgroundMaterial;
  89052. }(BABYLON.PushMaterial));
  89053. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89054. })(BABYLON || (BABYLON = {}));
  89055. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89056. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89057. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89058. s = arguments[i];
  89059. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89060. t[p] = s[p];
  89061. }
  89062. return t;
  89063. };
  89064. var BABYLON;
  89065. (function (BABYLON) {
  89066. /**
  89067. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89068. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89069. * It also helps with the default setup of your imageProcessing configuration.
  89070. */
  89071. var EnvironmentHelper = /** @class */ (function () {
  89072. /**
  89073. * constructor
  89074. * @param options
  89075. * @param scene The scene to add the material to
  89076. */
  89077. function EnvironmentHelper(options, scene) {
  89078. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89079. this._scene = scene;
  89080. this._setupBackground();
  89081. this._setupImageProcessing();
  89082. }
  89083. /**
  89084. * Creates the default options for the helper.
  89085. */
  89086. EnvironmentHelper._getDefaultOptions = function () {
  89087. return {
  89088. createGround: true,
  89089. groundSize: 15,
  89090. groundTexture: this._groundTextureCDNUrl,
  89091. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89092. groundOpacity: 0.9,
  89093. enableGroundShadow: true,
  89094. groundShadowLevel: 0.5,
  89095. enableGroundMirror: false,
  89096. groundMirrorSizeRatio: 0.3,
  89097. groundMirrorBlurKernel: 64,
  89098. groundMirrorAmount: 1,
  89099. groundMirrorFresnelWeight: 1,
  89100. groundMirrorFallOffDistance: 0,
  89101. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89102. groundYBias: 0.00001,
  89103. createSkybox: true,
  89104. skyboxSize: 20,
  89105. skyboxTexture: this._skyboxTextureCDNUrl,
  89106. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89107. backgroundYRotation: 0,
  89108. sizeAuto: true,
  89109. rootPosition: BABYLON.Vector3.Zero(),
  89110. setupImageProcessing: true,
  89111. environmentTexture: this._environmentTextureCDNUrl,
  89112. cameraExposure: 0.8,
  89113. cameraContrast: 1.2,
  89114. toneMappingEnabled: true,
  89115. };
  89116. };
  89117. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89118. /**
  89119. * Gets the root mesh created by the helper.
  89120. */
  89121. get: function () {
  89122. return this._rootMesh;
  89123. },
  89124. enumerable: true,
  89125. configurable: true
  89126. });
  89127. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89128. /**
  89129. * Gets the skybox created by the helper.
  89130. */
  89131. get: function () {
  89132. return this._skybox;
  89133. },
  89134. enumerable: true,
  89135. configurable: true
  89136. });
  89137. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89138. /**
  89139. * Gets the skybox texture created by the helper.
  89140. */
  89141. get: function () {
  89142. return this._skyboxTexture;
  89143. },
  89144. enumerable: true,
  89145. configurable: true
  89146. });
  89147. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89148. /**
  89149. * Gets the skybox material created by the helper.
  89150. */
  89151. get: function () {
  89152. return this._skyboxMaterial;
  89153. },
  89154. enumerable: true,
  89155. configurable: true
  89156. });
  89157. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89158. /**
  89159. * Gets the ground mesh created by the helper.
  89160. */
  89161. get: function () {
  89162. return this._ground;
  89163. },
  89164. enumerable: true,
  89165. configurable: true
  89166. });
  89167. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89168. /**
  89169. * Gets the ground texture created by the helper.
  89170. */
  89171. get: function () {
  89172. return this._groundTexture;
  89173. },
  89174. enumerable: true,
  89175. configurable: true
  89176. });
  89177. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89178. /**
  89179. * Gets the ground mirror created by the helper.
  89180. */
  89181. get: function () {
  89182. return this._groundMirror;
  89183. },
  89184. enumerable: true,
  89185. configurable: true
  89186. });
  89187. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89188. /**
  89189. * Gets the ground mirror render list to helps pushing the meshes
  89190. * you wish in the ground reflection.
  89191. */
  89192. get: function () {
  89193. if (this._groundMirror) {
  89194. return this._groundMirror.renderList;
  89195. }
  89196. return null;
  89197. },
  89198. enumerable: true,
  89199. configurable: true
  89200. });
  89201. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89202. /**
  89203. * Gets the ground material created by the helper.
  89204. */
  89205. get: function () {
  89206. return this._groundMaterial;
  89207. },
  89208. enumerable: true,
  89209. configurable: true
  89210. });
  89211. /**
  89212. * Updates the background according to the new options
  89213. * @param options
  89214. */
  89215. EnvironmentHelper.prototype.updateOptions = function (options) {
  89216. var newOptions = __assign({}, this._options, options);
  89217. if (this._ground && !newOptions.createGround) {
  89218. this._ground.dispose();
  89219. this._ground = null;
  89220. }
  89221. if (this._groundMaterial && !newOptions.createGround) {
  89222. this._groundMaterial.dispose();
  89223. this._groundMaterial = null;
  89224. }
  89225. if (this._groundTexture) {
  89226. if (this._options.groundTexture != newOptions.groundTexture) {
  89227. this._groundTexture.dispose();
  89228. this._groundTexture = null;
  89229. }
  89230. }
  89231. if (this._skybox && !newOptions.createSkybox) {
  89232. this._skybox.dispose();
  89233. this._skybox = null;
  89234. }
  89235. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89236. this._skyboxMaterial.dispose();
  89237. this._skyboxMaterial = null;
  89238. }
  89239. if (this._skyboxTexture) {
  89240. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89241. this._skyboxTexture.dispose();
  89242. this._skyboxTexture = null;
  89243. }
  89244. }
  89245. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89246. this._groundMirror.dispose();
  89247. this._groundMirror = null;
  89248. }
  89249. if (this._scene.environmentTexture) {
  89250. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89251. this._scene.environmentTexture.dispose();
  89252. }
  89253. }
  89254. this._options = newOptions;
  89255. this._setupBackground();
  89256. this._setupImageProcessing();
  89257. };
  89258. /**
  89259. * Sets the primary color of all the available elements.
  89260. * @param color
  89261. */
  89262. EnvironmentHelper.prototype.setMainColor = function (color) {
  89263. if (this.groundMaterial) {
  89264. this.groundMaterial.primaryColor = color;
  89265. }
  89266. if (this.skyboxMaterial) {
  89267. this.skyboxMaterial.primaryColor = color;
  89268. }
  89269. if (this.groundMirror) {
  89270. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89271. }
  89272. };
  89273. /**
  89274. * Setup the image processing according to the specified options.
  89275. */
  89276. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89277. if (this._options.setupImageProcessing) {
  89278. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89279. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89280. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89281. this._setupEnvironmentTexture();
  89282. }
  89283. };
  89284. /**
  89285. * Setup the environment texture according to the specified options.
  89286. */
  89287. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89288. if (this._scene.environmentTexture) {
  89289. return;
  89290. }
  89291. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89292. this._scene.environmentTexture = this._options.environmentTexture;
  89293. return;
  89294. }
  89295. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89296. this._scene.environmentTexture = environmentTexture;
  89297. };
  89298. /**
  89299. * Setup the background according to the specified options.
  89300. */
  89301. EnvironmentHelper.prototype._setupBackground = function () {
  89302. if (!this._rootMesh) {
  89303. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89304. }
  89305. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89306. var sceneSize = this._getSceneSize();
  89307. if (this._options.createGround) {
  89308. this._setupGround(sceneSize);
  89309. this._setupGroundMaterial();
  89310. this._setupGroundDiffuseTexture();
  89311. if (this._options.enableGroundMirror) {
  89312. this._setupGroundMirrorTexture(sceneSize);
  89313. }
  89314. this._setupMirrorInGroundMaterial();
  89315. }
  89316. if (this._options.createSkybox) {
  89317. this._setupSkybox(sceneSize);
  89318. this._setupSkyboxMaterial();
  89319. this._setupSkyboxReflectionTexture();
  89320. }
  89321. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89322. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89323. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89324. };
  89325. /**
  89326. * Get the scene sizes according to the setup.
  89327. */
  89328. EnvironmentHelper.prototype._getSceneSize = function () {
  89329. var _this = this;
  89330. var groundSize = this._options.groundSize;
  89331. var skyboxSize = this._options.skyboxSize;
  89332. var rootPosition = this._options.rootPosition;
  89333. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89334. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89335. }
  89336. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89337. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89338. });
  89339. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89340. if (this._options.sizeAuto) {
  89341. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89342. this._scene.activeCamera.upperRadiusLimit) {
  89343. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89344. skyboxSize = groundSize;
  89345. }
  89346. var sceneDiagonalLenght = sceneDiagonal.length();
  89347. if (sceneDiagonalLenght > groundSize) {
  89348. groundSize = sceneDiagonalLenght * 2;
  89349. skyboxSize = groundSize;
  89350. }
  89351. // 10 % bigger.
  89352. groundSize *= 1.1;
  89353. skyboxSize *= 1.5;
  89354. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89355. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89356. }
  89357. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89358. };
  89359. /**
  89360. * Setup the ground according to the specified options.
  89361. */
  89362. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89363. var _this = this;
  89364. if (!this._ground) {
  89365. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89366. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89367. this._ground.parent = this._rootMesh;
  89368. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89369. }
  89370. this._ground.receiveShadows = this._options.enableGroundShadow;
  89371. };
  89372. /**
  89373. * Setup the ground material according to the specified options.
  89374. */
  89375. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89376. if (!this._groundMaterial) {
  89377. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89378. }
  89379. this._groundMaterial.alpha = this._options.groundOpacity;
  89380. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89381. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89382. this._groundMaterial.primaryLevel = 1;
  89383. this._groundMaterial.primaryColor = this._options.groundColor;
  89384. this._groundMaterial.secondaryLevel = 0;
  89385. this._groundMaterial.tertiaryLevel = 0;
  89386. this._groundMaterial.useRGBColor = false;
  89387. this._groundMaterial.enableNoise = true;
  89388. if (this._ground) {
  89389. this._ground.material = this._groundMaterial;
  89390. }
  89391. };
  89392. /**
  89393. * Setup the ground diffuse texture according to the specified options.
  89394. */
  89395. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89396. if (!this._groundMaterial) {
  89397. return;
  89398. }
  89399. if (this._groundTexture) {
  89400. return;
  89401. }
  89402. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89403. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89404. return;
  89405. }
  89406. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89407. diffuseTexture.gammaSpace = false;
  89408. diffuseTexture.hasAlpha = true;
  89409. this._groundMaterial.diffuseTexture = diffuseTexture;
  89410. };
  89411. /**
  89412. * Setup the ground mirror texture according to the specified options.
  89413. */
  89414. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89415. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89416. if (!this._groundMirror) {
  89417. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89418. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89419. this._groundMirror.anisotropicFilteringLevel = 1;
  89420. this._groundMirror.wrapU = wrapping;
  89421. this._groundMirror.wrapV = wrapping;
  89422. this._groundMirror.gammaSpace = false;
  89423. if (this._groundMirror.renderList) {
  89424. for (var i = 0; i < this._scene.meshes.length; i++) {
  89425. var mesh = this._scene.meshes[i];
  89426. if (mesh !== this._ground &&
  89427. mesh !== this._skybox &&
  89428. mesh !== this._rootMesh) {
  89429. this._groundMirror.renderList.push(mesh);
  89430. }
  89431. }
  89432. }
  89433. }
  89434. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89435. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89436. };
  89437. /**
  89438. * Setup the ground to receive the mirror texture.
  89439. */
  89440. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89441. if (this._groundMaterial) {
  89442. this._groundMaterial.reflectionTexture = this._groundMirror;
  89443. this._groundMaterial.reflectionFresnel = true;
  89444. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89445. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89446. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89447. }
  89448. };
  89449. /**
  89450. * Setup the skybox according to the specified options.
  89451. */
  89452. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89453. var _this = this;
  89454. if (!this._skybox) {
  89455. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89456. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89457. }
  89458. this._skybox.parent = this._rootMesh;
  89459. };
  89460. /**
  89461. * Setup the skybox material according to the specified options.
  89462. */
  89463. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89464. if (!this._skybox) {
  89465. return;
  89466. }
  89467. if (!this._skyboxMaterial) {
  89468. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89469. }
  89470. this._skyboxMaterial.useRGBColor = false;
  89471. this._skyboxMaterial.primaryLevel = 1;
  89472. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89473. this._skyboxMaterial.secondaryLevel = 0;
  89474. this._skyboxMaterial.tertiaryLevel = 0;
  89475. this._skyboxMaterial.enableNoise = true;
  89476. this._skybox.material = this._skyboxMaterial;
  89477. };
  89478. /**
  89479. * Setup the skybox reflection texture according to the specified options.
  89480. */
  89481. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89482. if (!this._skyboxMaterial) {
  89483. return;
  89484. }
  89485. if (this._skyboxTexture) {
  89486. return;
  89487. }
  89488. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89489. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89490. return;
  89491. }
  89492. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89493. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89494. this._skyboxTexture.gammaSpace = false;
  89495. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89496. };
  89497. /**
  89498. * Dispose all the elements created by the Helper.
  89499. */
  89500. EnvironmentHelper.prototype.dispose = function () {
  89501. if (this._groundMaterial) {
  89502. this._groundMaterial.dispose(true, true);
  89503. }
  89504. if (this._skyboxMaterial) {
  89505. this._skyboxMaterial.dispose(true, true);
  89506. }
  89507. this._rootMesh.dispose(false);
  89508. };
  89509. /**
  89510. * Default ground texture URL.
  89511. */
  89512. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89513. /**
  89514. * Default skybox texture URL.
  89515. */
  89516. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89517. /**
  89518. * Default environment texture URL.
  89519. */
  89520. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89521. return EnvironmentHelper;
  89522. }());
  89523. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89524. })(BABYLON || (BABYLON = {}));
  89525. //# sourceMappingURL=babylon.environmentHelper.js.map
  89526. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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)\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#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\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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*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(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","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;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\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}","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}","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  89527. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\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,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,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,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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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};","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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  89528. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89529. var BABYLON;
  89530. (function (BABYLON) {
  89531. var GridMaterialDefines = /** @class */ (function (_super) {
  89532. __extends(GridMaterialDefines, _super);
  89533. function GridMaterialDefines() {
  89534. var _this = _super.call(this) || this;
  89535. _this.TRANSPARENT = false;
  89536. _this.FOG = false;
  89537. _this.PREMULTIPLYALPHA = false;
  89538. _this.rebuild();
  89539. return _this;
  89540. }
  89541. return GridMaterialDefines;
  89542. }(BABYLON.MaterialDefines));
  89543. /**
  89544. * The grid materials allows you to wrap any shape with a grid.
  89545. * Colors are customizable.
  89546. */
  89547. var GridMaterial = /** @class */ (function (_super) {
  89548. __extends(GridMaterial, _super);
  89549. /**
  89550. * constructor
  89551. * @param name The name given to the material in order to identify it afterwards.
  89552. * @param scene The scene the material is used in.
  89553. */
  89554. function GridMaterial(name, scene) {
  89555. var _this = _super.call(this, name, scene) || this;
  89556. /**
  89557. * Main color of the grid (e.g. between lines)
  89558. */
  89559. _this.mainColor = BABYLON.Color3.Black();
  89560. /**
  89561. * Color of the grid lines.
  89562. */
  89563. _this.lineColor = BABYLON.Color3.Teal();
  89564. /**
  89565. * The scale of the grid compared to unit.
  89566. */
  89567. _this.gridRatio = 1.0;
  89568. /**
  89569. * Allows setting an offset for the grid lines.
  89570. */
  89571. _this.gridOffset = BABYLON.Vector3.Zero();
  89572. /**
  89573. * The frequency of thicker lines.
  89574. */
  89575. _this.majorUnitFrequency = 10;
  89576. /**
  89577. * The visibility of minor units in the grid.
  89578. */
  89579. _this.minorUnitVisibility = 0.33;
  89580. /**
  89581. * The grid opacity outside of the lines.
  89582. */
  89583. _this.opacity = 1.0;
  89584. /**
  89585. * Determine RBG output is premultiplied by alpha value.
  89586. */
  89587. _this.preMultiplyAlpha = false;
  89588. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89589. return _this;
  89590. }
  89591. /**
  89592. * Returns wehter or not the grid requires alpha blending.
  89593. */
  89594. GridMaterial.prototype.needAlphaBlending = function () {
  89595. return this.opacity < 1.0;
  89596. };
  89597. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89598. return this.needAlphaBlending();
  89599. };
  89600. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89601. if (this.isFrozen) {
  89602. if (this._wasPreviouslyReady && subMesh.effect) {
  89603. return true;
  89604. }
  89605. }
  89606. if (!subMesh._materialDefines) {
  89607. subMesh._materialDefines = new GridMaterialDefines();
  89608. }
  89609. var defines = subMesh._materialDefines;
  89610. var scene = this.getScene();
  89611. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89612. if (this._renderId === scene.getRenderId()) {
  89613. return true;
  89614. }
  89615. }
  89616. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89617. defines.TRANSPARENT = !defines.TRANSPARENT;
  89618. defines.markAsUnprocessed();
  89619. }
  89620. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89621. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89622. defines.markAsUnprocessed();
  89623. }
  89624. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89625. // Get correct effect
  89626. if (defines.isDirty) {
  89627. defines.markAsProcessed();
  89628. scene.resetCachedMaterial();
  89629. // Attributes
  89630. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89631. // Defines
  89632. var join = defines.toString();
  89633. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89634. }
  89635. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89636. return false;
  89637. }
  89638. this._renderId = scene.getRenderId();
  89639. this._wasPreviouslyReady = true;
  89640. return true;
  89641. };
  89642. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89643. var scene = this.getScene();
  89644. var defines = subMesh._materialDefines;
  89645. if (!defines) {
  89646. return;
  89647. }
  89648. var effect = subMesh.effect;
  89649. if (!effect) {
  89650. return;
  89651. }
  89652. this._activeEffect = effect;
  89653. // Matrices
  89654. this.bindOnlyWorldMatrix(world);
  89655. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89656. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89657. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89658. // Uniforms
  89659. if (this._mustRebind(scene, effect)) {
  89660. this._activeEffect.setColor3("mainColor", this.mainColor);
  89661. this._activeEffect.setColor3("lineColor", this.lineColor);
  89662. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89663. this._gridControl.x = this.gridRatio;
  89664. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89665. this._gridControl.z = this.minorUnitVisibility;
  89666. this._gridControl.w = this.opacity;
  89667. this._activeEffect.setVector4("gridControl", this._gridControl);
  89668. }
  89669. // Fog
  89670. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89671. this._afterBind(mesh, this._activeEffect);
  89672. };
  89673. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89674. _super.prototype.dispose.call(this, forceDisposeEffect);
  89675. };
  89676. GridMaterial.prototype.clone = function (name) {
  89677. var _this = this;
  89678. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89679. };
  89680. GridMaterial.prototype.serialize = function () {
  89681. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89682. serializationObject.customType = "BABYLON.GridMaterial";
  89683. return serializationObject;
  89684. };
  89685. GridMaterial.prototype.getClassName = function () {
  89686. return "GridMaterial";
  89687. };
  89688. GridMaterial.Parse = function (source, scene, rootUrl) {
  89689. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89690. };
  89691. __decorate([
  89692. BABYLON.serializeAsColor3()
  89693. ], GridMaterial.prototype, "mainColor", void 0);
  89694. __decorate([
  89695. BABYLON.serializeAsColor3()
  89696. ], GridMaterial.prototype, "lineColor", void 0);
  89697. __decorate([
  89698. BABYLON.serialize()
  89699. ], GridMaterial.prototype, "gridRatio", void 0);
  89700. __decorate([
  89701. BABYLON.serializeAsColor3()
  89702. ], GridMaterial.prototype, "gridOffset", void 0);
  89703. __decorate([
  89704. BABYLON.serialize()
  89705. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89706. __decorate([
  89707. BABYLON.serialize()
  89708. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89709. __decorate([
  89710. BABYLON.serialize()
  89711. ], GridMaterial.prototype, "opacity", void 0);
  89712. __decorate([
  89713. BABYLON.serialize()
  89714. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89715. return GridMaterial;
  89716. }(BABYLON.PushMaterial));
  89717. BABYLON.GridMaterial = GridMaterial;
  89718. })(BABYLON || (BABYLON = {}));
  89719. //# sourceMappingURL=babylon.gridmaterial.js.map
  89720. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  89721. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  89722. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89723. var BABYLON;
  89724. (function (BABYLON) {
  89725. var GLTFLoaderCoordinateSystemMode;
  89726. (function (GLTFLoaderCoordinateSystemMode) {
  89727. /**
  89728. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89729. */
  89730. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89731. /**
  89732. * Sets the useRightHandedSystem flag on the scene.
  89733. */
  89734. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89735. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89736. var GLTFLoaderAnimationStartMode;
  89737. (function (GLTFLoaderAnimationStartMode) {
  89738. /**
  89739. * No animation will start.
  89740. */
  89741. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89742. /**
  89743. * The first animation will start.
  89744. */
  89745. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89746. /**
  89747. * All animations will start.
  89748. */
  89749. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89750. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89751. var GLTFLoaderState;
  89752. (function (GLTFLoaderState) {
  89753. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89754. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89755. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89756. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89757. var GLTFFileLoader = /** @class */ (function () {
  89758. function GLTFFileLoader() {
  89759. // #region Common options
  89760. /**
  89761. * Raised when the asset has been parsed.
  89762. * The data.json property stores the glTF JSON.
  89763. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89764. */
  89765. this.onParsedObservable = new BABYLON.Observable();
  89766. // #endregion
  89767. // #region V2 options
  89768. /**
  89769. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89770. */
  89771. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89772. /**
  89773. * The animation start mode (NONE, FIRST, ALL).
  89774. */
  89775. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89776. /**
  89777. * Set to true to compile materials before raising the success callback.
  89778. */
  89779. this.compileMaterials = false;
  89780. /**
  89781. * Set to true to also compile materials with clip planes.
  89782. */
  89783. this.useClipPlane = false;
  89784. /**
  89785. * Set to true to compile shadow generators before raising the success callback.
  89786. */
  89787. this.compileShadowGenerators = false;
  89788. /**
  89789. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89790. */
  89791. this.onMeshLoadedObservable = new BABYLON.Observable();
  89792. /**
  89793. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89794. */
  89795. this.onTextureLoadedObservable = new BABYLON.Observable();
  89796. /**
  89797. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89798. */
  89799. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89800. /**
  89801. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89802. * For assets with LODs, raised when all of the LODs are complete.
  89803. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89804. */
  89805. this.onCompleteObservable = new BABYLON.Observable();
  89806. /**
  89807. * Raised when the loader is disposed.
  89808. */
  89809. this.onDisposeObservable = new BABYLON.Observable();
  89810. /**
  89811. * Raised after a loader extension is created.
  89812. * Set additional options for a loader extension in this event.
  89813. */
  89814. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89815. // #endregion
  89816. this._loader = null;
  89817. this.name = "gltf";
  89818. this.extensions = {
  89819. ".gltf": { isBinary: false },
  89820. ".glb": { isBinary: true }
  89821. };
  89822. }
  89823. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89824. set: function (callback) {
  89825. if (this._onParsedObserver) {
  89826. this.onParsedObservable.remove(this._onParsedObserver);
  89827. }
  89828. this._onParsedObserver = this.onParsedObservable.add(callback);
  89829. },
  89830. enumerable: true,
  89831. configurable: true
  89832. });
  89833. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89834. set: function (callback) {
  89835. if (this._onMeshLoadedObserver) {
  89836. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89837. }
  89838. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89839. },
  89840. enumerable: true,
  89841. configurable: true
  89842. });
  89843. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89844. set: function (callback) {
  89845. if (this._onTextureLoadedObserver) {
  89846. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89847. }
  89848. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89849. },
  89850. enumerable: true,
  89851. configurable: true
  89852. });
  89853. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89854. set: function (callback) {
  89855. if (this._onMaterialLoadedObserver) {
  89856. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89857. }
  89858. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89859. },
  89860. enumerable: true,
  89861. configurable: true
  89862. });
  89863. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89864. set: function (callback) {
  89865. if (this._onCompleteObserver) {
  89866. this.onCompleteObservable.remove(this._onCompleteObserver);
  89867. }
  89868. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89869. },
  89870. enumerable: true,
  89871. configurable: true
  89872. });
  89873. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89874. set: function (callback) {
  89875. if (this._onDisposeObserver) {
  89876. this.onDisposeObservable.remove(this._onDisposeObserver);
  89877. }
  89878. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89879. },
  89880. enumerable: true,
  89881. configurable: true
  89882. });
  89883. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89884. set: function (callback) {
  89885. if (this._onExtensionLoadedObserver) {
  89886. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89887. }
  89888. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89889. },
  89890. enumerable: true,
  89891. configurable: true
  89892. });
  89893. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89894. /**
  89895. * The loader state or null if not active.
  89896. */
  89897. get: function () {
  89898. return this._loader ? this._loader.state : null;
  89899. },
  89900. enumerable: true,
  89901. configurable: true
  89902. });
  89903. /**
  89904. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89905. */
  89906. GLTFFileLoader.prototype.dispose = function () {
  89907. if (this._loader) {
  89908. this._loader.dispose();
  89909. this._loader = null;
  89910. }
  89911. this.onMeshLoadedObservable.clear();
  89912. this.onTextureLoadedObservable.clear();
  89913. this.onMaterialLoadedObservable.clear();
  89914. this.onDisposeObservable.notifyObservers(this);
  89915. this.onDisposeObservable.clear();
  89916. };
  89917. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89918. var _this = this;
  89919. return Promise.resolve().then(function () {
  89920. var loaderData = _this._parse(data);
  89921. _this._loader = _this._getLoader(loaderData);
  89922. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89923. });
  89924. };
  89925. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89926. var _this = this;
  89927. return Promise.resolve().then(function () {
  89928. var loaderData = _this._parse(data);
  89929. _this._loader = _this._getLoader(loaderData);
  89930. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89931. });
  89932. };
  89933. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89934. var _this = this;
  89935. return Promise.resolve().then(function () {
  89936. var loaderData = _this._parse(data);
  89937. _this._loader = _this._getLoader(loaderData);
  89938. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89939. var container = new BABYLON.AssetContainer(scene);
  89940. Array.prototype.push.apply(container.meshes, result.meshes);
  89941. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89942. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89943. container.removeAllFromScene();
  89944. return container;
  89945. });
  89946. });
  89947. };
  89948. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  89949. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  89950. };
  89951. GLTFFileLoader.prototype.createPlugin = function () {
  89952. return new GLTFFileLoader();
  89953. };
  89954. GLTFFileLoader.prototype._parse = function (data) {
  89955. var parsedData;
  89956. if (data instanceof ArrayBuffer) {
  89957. parsedData = GLTFFileLoader._parseBinary(data);
  89958. }
  89959. else {
  89960. parsedData = {
  89961. json: JSON.parse(data),
  89962. bin: null
  89963. };
  89964. }
  89965. this.onParsedObservable.notifyObservers(parsedData);
  89966. this.onParsedObservable.clear();
  89967. return parsedData;
  89968. };
  89969. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  89970. var _this = this;
  89971. var loaderVersion = { major: 2, minor: 0 };
  89972. var asset = loaderData.json.asset || {};
  89973. var version = GLTFFileLoader._parseVersion(asset.version);
  89974. if (!version) {
  89975. throw new Error("Invalid version: " + asset.version);
  89976. }
  89977. if (asset.minVersion !== undefined) {
  89978. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  89979. if (!minVersion) {
  89980. throw new Error("Invalid minimum version: " + asset.minVersion);
  89981. }
  89982. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  89983. throw new Error("Incompatible minimum version: " + asset.minVersion);
  89984. }
  89985. }
  89986. var createLoaders = {
  89987. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  89988. 2: GLTFFileLoader.CreateGLTFLoaderV2
  89989. };
  89990. var createLoader = createLoaders[version.major];
  89991. if (!createLoader) {
  89992. throw new Error("Unsupported version: " + asset.version);
  89993. }
  89994. var loader = createLoader();
  89995. loader.coordinateSystemMode = this.coordinateSystemMode;
  89996. loader.animationStartMode = this.animationStartMode;
  89997. loader.compileMaterials = this.compileMaterials;
  89998. loader.useClipPlane = this.useClipPlane;
  89999. loader.compileShadowGenerators = this.compileShadowGenerators;
  90000. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90001. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90002. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90003. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90004. loader.onCompleteObservable.add(function () {
  90005. _this.onMeshLoadedObservable.clear();
  90006. _this.onTextureLoadedObservable.clear();
  90007. _this.onMaterialLoadedObservable.clear();
  90008. _this.onCompleteObservable.notifyObservers(_this);
  90009. _this.onCompleteObservable.clear();
  90010. });
  90011. return loader;
  90012. };
  90013. GLTFFileLoader._parseBinary = function (data) {
  90014. var Binary = {
  90015. Magic: 0x46546C67
  90016. };
  90017. var binaryReader = new BinaryReader(data);
  90018. var magic = binaryReader.readUint32();
  90019. if (magic !== Binary.Magic) {
  90020. throw new Error("Unexpected magic: " + magic);
  90021. }
  90022. var version = binaryReader.readUint32();
  90023. switch (version) {
  90024. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90025. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90026. }
  90027. throw new Error("Unsupported version: " + version);
  90028. };
  90029. GLTFFileLoader._parseV1 = function (binaryReader) {
  90030. var ContentFormat = {
  90031. JSON: 0
  90032. };
  90033. var length = binaryReader.readUint32();
  90034. if (length != binaryReader.getLength()) {
  90035. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90036. }
  90037. var contentLength = binaryReader.readUint32();
  90038. var contentFormat = binaryReader.readUint32();
  90039. var content;
  90040. switch (contentFormat) {
  90041. case ContentFormat.JSON: {
  90042. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90043. break;
  90044. }
  90045. default: {
  90046. throw new Error("Unexpected content format: " + contentFormat);
  90047. }
  90048. }
  90049. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90050. var body = binaryReader.readUint8Array(bytesRemaining);
  90051. return {
  90052. json: content,
  90053. bin: body
  90054. };
  90055. };
  90056. GLTFFileLoader._parseV2 = function (binaryReader) {
  90057. var ChunkFormat = {
  90058. JSON: 0x4E4F534A,
  90059. BIN: 0x004E4942
  90060. };
  90061. var length = binaryReader.readUint32();
  90062. if (length !== binaryReader.getLength()) {
  90063. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90064. }
  90065. // JSON chunk
  90066. var chunkLength = binaryReader.readUint32();
  90067. var chunkFormat = binaryReader.readUint32();
  90068. if (chunkFormat !== ChunkFormat.JSON) {
  90069. throw new Error("First chunk format is not JSON");
  90070. }
  90071. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90072. // Look for BIN chunk
  90073. var bin = null;
  90074. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90075. var chunkLength_1 = binaryReader.readUint32();
  90076. var chunkFormat_1 = binaryReader.readUint32();
  90077. switch (chunkFormat_1) {
  90078. case ChunkFormat.JSON: {
  90079. throw new Error("Unexpected JSON chunk");
  90080. }
  90081. case ChunkFormat.BIN: {
  90082. bin = binaryReader.readUint8Array(chunkLength_1);
  90083. break;
  90084. }
  90085. default: {
  90086. // ignore unrecognized chunkFormat
  90087. binaryReader.skipBytes(chunkLength_1);
  90088. break;
  90089. }
  90090. }
  90091. }
  90092. return {
  90093. json: json,
  90094. bin: bin
  90095. };
  90096. };
  90097. GLTFFileLoader._parseVersion = function (version) {
  90098. if (version === "1.0" || version === "1.0.1") {
  90099. return {
  90100. major: 1,
  90101. minor: 0
  90102. };
  90103. }
  90104. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90105. if (!match) {
  90106. return null;
  90107. }
  90108. return {
  90109. major: parseInt(match[1]),
  90110. minor: parseInt(match[2])
  90111. };
  90112. };
  90113. GLTFFileLoader._compareVersion = function (a, b) {
  90114. if (a.major > b.major)
  90115. return 1;
  90116. if (a.major < b.major)
  90117. return -1;
  90118. if (a.minor > b.minor)
  90119. return 1;
  90120. if (a.minor < b.minor)
  90121. return -1;
  90122. return 0;
  90123. };
  90124. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90125. var result = "";
  90126. var length = buffer.byteLength;
  90127. for (var i = 0; i < length; i++) {
  90128. result += String.fromCharCode(buffer[i]);
  90129. }
  90130. return result;
  90131. };
  90132. // #endregion
  90133. // #region V1 options
  90134. GLTFFileLoader.IncrementalLoading = true;
  90135. GLTFFileLoader.HomogeneousCoordinates = false;
  90136. return GLTFFileLoader;
  90137. }());
  90138. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90139. var BinaryReader = /** @class */ (function () {
  90140. function BinaryReader(arrayBuffer) {
  90141. this._arrayBuffer = arrayBuffer;
  90142. this._dataView = new DataView(arrayBuffer);
  90143. this._byteOffset = 0;
  90144. }
  90145. BinaryReader.prototype.getPosition = function () {
  90146. return this._byteOffset;
  90147. };
  90148. BinaryReader.prototype.getLength = function () {
  90149. return this._arrayBuffer.byteLength;
  90150. };
  90151. BinaryReader.prototype.readUint32 = function () {
  90152. var value = this._dataView.getUint32(this._byteOffset, true);
  90153. this._byteOffset += 4;
  90154. return value;
  90155. };
  90156. BinaryReader.prototype.readUint8Array = function (length) {
  90157. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90158. this._byteOffset += length;
  90159. return value;
  90160. };
  90161. BinaryReader.prototype.skipBytes = function (length) {
  90162. this._byteOffset += length;
  90163. };
  90164. return BinaryReader;
  90165. }());
  90166. if (BABYLON.SceneLoader) {
  90167. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90168. }
  90169. })(BABYLON || (BABYLON = {}));
  90170. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90171. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90172. var BABYLON;
  90173. (function (BABYLON) {
  90174. var GLTF1;
  90175. (function (GLTF1) {
  90176. /**
  90177. * Enums
  90178. */
  90179. var EComponentType;
  90180. (function (EComponentType) {
  90181. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90182. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90183. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90184. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90185. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90186. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90187. var EShaderType;
  90188. (function (EShaderType) {
  90189. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90190. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90191. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90192. var EParameterType;
  90193. (function (EParameterType) {
  90194. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90195. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90196. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90197. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90198. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90199. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90200. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90201. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90202. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90203. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90204. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90205. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90206. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90207. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90208. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90209. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90210. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90211. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90212. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90213. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90214. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90215. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90216. var ETextureWrapMode;
  90217. (function (ETextureWrapMode) {
  90218. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90219. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90220. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90221. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90222. var ETextureFilterType;
  90223. (function (ETextureFilterType) {
  90224. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90225. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90226. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90227. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90228. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90229. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90230. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90231. var ETextureFormat;
  90232. (function (ETextureFormat) {
  90233. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90234. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90235. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90236. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90237. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90238. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90239. var ECullingType;
  90240. (function (ECullingType) {
  90241. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90242. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90243. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90244. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90245. var EBlendingFunction;
  90246. (function (EBlendingFunction) {
  90247. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90248. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90249. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90250. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90251. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90252. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90253. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90254. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90255. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90256. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90257. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90258. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90259. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90260. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90261. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90262. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90263. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90264. })(BABYLON || (BABYLON = {}));
  90265. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90266. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90267. var BABYLON;
  90268. (function (BABYLON) {
  90269. var GLTF1;
  90270. (function (GLTF1) {
  90271. /**
  90272. * Tokenizer. Used for shaders compatibility
  90273. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90274. */
  90275. var ETokenType;
  90276. (function (ETokenType) {
  90277. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90278. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90279. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90280. })(ETokenType || (ETokenType = {}));
  90281. var Tokenizer = /** @class */ (function () {
  90282. function Tokenizer(toParse) {
  90283. this._pos = 0;
  90284. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90285. this._toParse = toParse;
  90286. this._maxPos = toParse.length;
  90287. }
  90288. Tokenizer.prototype.getNextToken = function () {
  90289. if (this.isEnd())
  90290. return ETokenType.END_OF_INPUT;
  90291. this.currentString = this.read();
  90292. this.currentToken = ETokenType.UNKNOWN;
  90293. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90294. this.currentToken = ETokenType.IDENTIFIER;
  90295. this.currentIdentifier = this.currentString;
  90296. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90297. this.currentIdentifier += this.currentString;
  90298. this.forward();
  90299. }
  90300. }
  90301. return this.currentToken;
  90302. };
  90303. Tokenizer.prototype.peek = function () {
  90304. return this._toParse[this._pos];
  90305. };
  90306. Tokenizer.prototype.read = function () {
  90307. return this._toParse[this._pos++];
  90308. };
  90309. Tokenizer.prototype.forward = function () {
  90310. this._pos++;
  90311. };
  90312. Tokenizer.prototype.isEnd = function () {
  90313. return this._pos >= this._maxPos;
  90314. };
  90315. return Tokenizer;
  90316. }());
  90317. /**
  90318. * Values
  90319. */
  90320. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90321. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90322. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90323. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90324. /**
  90325. * Parse
  90326. */
  90327. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90328. for (var buf in parsedBuffers) {
  90329. var parsedBuffer = parsedBuffers[buf];
  90330. gltfRuntime.buffers[buf] = parsedBuffer;
  90331. gltfRuntime.buffersCount++;
  90332. }
  90333. };
  90334. var parseShaders = function (parsedShaders, gltfRuntime) {
  90335. for (var sha in parsedShaders) {
  90336. var parsedShader = parsedShaders[sha];
  90337. gltfRuntime.shaders[sha] = parsedShader;
  90338. gltfRuntime.shaderscount++;
  90339. }
  90340. };
  90341. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90342. for (var object in parsedObjects) {
  90343. var parsedObject = parsedObjects[object];
  90344. gltfRuntime[runtimeProperty][object] = parsedObject;
  90345. }
  90346. };
  90347. /**
  90348. * Utils
  90349. */
  90350. var normalizeUVs = function (buffer) {
  90351. if (!buffer) {
  90352. return;
  90353. }
  90354. for (var i = 0; i < buffer.length / 2; i++) {
  90355. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90356. }
  90357. };
  90358. var getAttribute = function (attributeParameter) {
  90359. if (attributeParameter.semantic === "NORMAL") {
  90360. return "normal";
  90361. }
  90362. else if (attributeParameter.semantic === "POSITION") {
  90363. return "position";
  90364. }
  90365. else if (attributeParameter.semantic === "JOINT") {
  90366. return "matricesIndices";
  90367. }
  90368. else if (attributeParameter.semantic === "WEIGHT") {
  90369. return "matricesWeights";
  90370. }
  90371. else if (attributeParameter.semantic === "COLOR") {
  90372. return "color";
  90373. }
  90374. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90375. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90376. return "uv" + (channel === 0 ? "" : channel + 1);
  90377. }
  90378. return null;
  90379. };
  90380. /**
  90381. * Loads and creates animations
  90382. */
  90383. var loadAnimations = function (gltfRuntime) {
  90384. for (var anim in gltfRuntime.animations) {
  90385. var animation = gltfRuntime.animations[anim];
  90386. if (!animation.channels || !animation.samplers) {
  90387. continue;
  90388. }
  90389. var lastAnimation = null;
  90390. for (var i = 0; i < animation.channels.length; i++) {
  90391. // Get parameters and load buffers
  90392. var channel = animation.channels[i];
  90393. var sampler = animation.samplers[channel.sampler];
  90394. if (!sampler) {
  90395. continue;
  90396. }
  90397. var inputData = null;
  90398. var outputData = null;
  90399. if (animation.parameters) {
  90400. inputData = animation.parameters[sampler.input];
  90401. outputData = animation.parameters[sampler.output];
  90402. }
  90403. else {
  90404. inputData = sampler.input;
  90405. outputData = sampler.output;
  90406. }
  90407. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90408. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90409. var targetID = channel.target.id;
  90410. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90411. if (targetNode === null) {
  90412. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90413. }
  90414. if (targetNode === null) {
  90415. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90416. continue;
  90417. }
  90418. var isBone = targetNode instanceof BABYLON.Bone;
  90419. // Get target path (position, rotation or scaling)
  90420. var targetPath = channel.target.path;
  90421. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90422. if (targetPathIndex !== -1) {
  90423. targetPath = babylonAnimationPaths[targetPathIndex];
  90424. }
  90425. // Determine animation type
  90426. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90427. if (!isBone) {
  90428. if (targetPath === "rotationQuaternion") {
  90429. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90430. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90431. }
  90432. else {
  90433. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90434. }
  90435. }
  90436. // Create animation and key frames
  90437. var babylonAnimation = null;
  90438. var keys = [];
  90439. var arrayOffset = 0;
  90440. var modifyKey = false;
  90441. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90442. babylonAnimation = lastAnimation;
  90443. modifyKey = true;
  90444. }
  90445. if (!modifyKey) {
  90446. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90447. }
  90448. // For each frame
  90449. for (var j = 0; j < bufferInput.length; j++) {
  90450. var value = null;
  90451. if (targetPath === "rotationQuaternion") {
  90452. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90453. arrayOffset += 4;
  90454. }
  90455. else {
  90456. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90457. arrayOffset += 3;
  90458. }
  90459. if (isBone) {
  90460. var bone = targetNode;
  90461. var translation = BABYLON.Vector3.Zero();
  90462. var rotationQuaternion = new BABYLON.Quaternion();
  90463. var scaling = BABYLON.Vector3.Zero();
  90464. // Warning on decompose
  90465. var mat = bone.getBaseMatrix();
  90466. if (modifyKey && lastAnimation) {
  90467. mat = lastAnimation.getKeys()[j].value;
  90468. }
  90469. mat.decompose(scaling, rotationQuaternion, translation);
  90470. if (targetPath === "position") {
  90471. translation = value;
  90472. }
  90473. else if (targetPath === "rotationQuaternion") {
  90474. rotationQuaternion = value;
  90475. }
  90476. else {
  90477. scaling = value;
  90478. }
  90479. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90480. }
  90481. if (!modifyKey) {
  90482. keys.push({
  90483. frame: bufferInput[j],
  90484. value: value
  90485. });
  90486. }
  90487. else if (lastAnimation) {
  90488. lastAnimation.getKeys()[j].value = value;
  90489. }
  90490. }
  90491. // Finish
  90492. if (!modifyKey && babylonAnimation) {
  90493. babylonAnimation.setKeys(keys);
  90494. targetNode.animations.push(babylonAnimation);
  90495. }
  90496. lastAnimation = babylonAnimation;
  90497. gltfRuntime.scene.stopAnimation(targetNode);
  90498. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90499. }
  90500. }
  90501. };
  90502. /**
  90503. * Returns the bones transformation matrix
  90504. */
  90505. var configureBoneTransformation = function (node) {
  90506. var mat = null;
  90507. if (node.translation || node.rotation || node.scale) {
  90508. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90509. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90510. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90511. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90512. }
  90513. else {
  90514. mat = BABYLON.Matrix.FromArray(node.matrix);
  90515. }
  90516. return mat;
  90517. };
  90518. /**
  90519. * Returns the parent bone
  90520. */
  90521. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90522. // Try to find
  90523. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90524. if (newSkeleton.bones[i].name === jointName) {
  90525. return newSkeleton.bones[i];
  90526. }
  90527. }
  90528. // Not found, search in gltf nodes
  90529. var nodes = gltfRuntime.nodes;
  90530. for (var nde in nodes) {
  90531. var node = nodes[nde];
  90532. if (!node.jointName) {
  90533. continue;
  90534. }
  90535. var children = node.children;
  90536. for (var i = 0; i < children.length; i++) {
  90537. var child = gltfRuntime.nodes[children[i]];
  90538. if (!child.jointName) {
  90539. continue;
  90540. }
  90541. if (child.jointName === jointName) {
  90542. var mat = configureBoneTransformation(node);
  90543. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90544. bone.id = nde;
  90545. return bone;
  90546. }
  90547. }
  90548. }
  90549. return null;
  90550. };
  90551. /**
  90552. * Returns the appropriate root node
  90553. */
  90554. var getNodeToRoot = function (nodesToRoot, id) {
  90555. for (var i = 0; i < nodesToRoot.length; i++) {
  90556. var nodeToRoot = nodesToRoot[i];
  90557. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90558. var child = nodeToRoot.node.children[j];
  90559. if (child === id) {
  90560. return nodeToRoot.bone;
  90561. }
  90562. }
  90563. }
  90564. return null;
  90565. };
  90566. /**
  90567. * Returns the node with the joint name
  90568. */
  90569. var getJointNode = function (gltfRuntime, jointName) {
  90570. var nodes = gltfRuntime.nodes;
  90571. var node = nodes[jointName];
  90572. if (node) {
  90573. return {
  90574. node: node,
  90575. id: jointName
  90576. };
  90577. }
  90578. for (var nde in nodes) {
  90579. node = nodes[nde];
  90580. if (node.jointName === jointName) {
  90581. return {
  90582. node: node,
  90583. id: nde
  90584. };
  90585. }
  90586. }
  90587. return null;
  90588. };
  90589. /**
  90590. * Checks if a nodes is in joints
  90591. */
  90592. var nodeIsInJoints = function (skins, id) {
  90593. for (var i = 0; i < skins.jointNames.length; i++) {
  90594. if (skins.jointNames[i] === id) {
  90595. return true;
  90596. }
  90597. }
  90598. return false;
  90599. };
  90600. /**
  90601. * Fills the nodes to root for bones and builds hierarchy
  90602. */
  90603. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90604. // Creates nodes for root
  90605. for (var nde in gltfRuntime.nodes) {
  90606. var node = gltfRuntime.nodes[nde];
  90607. var id = nde;
  90608. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90609. continue;
  90610. }
  90611. // Create node to root bone
  90612. var mat = configureBoneTransformation(node);
  90613. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90614. bone.id = id;
  90615. nodesToRoot.push({ bone: bone, node: node, id: id });
  90616. }
  90617. // Parenting
  90618. for (var i = 0; i < nodesToRoot.length; i++) {
  90619. var nodeToRoot = nodesToRoot[i];
  90620. var children = nodeToRoot.node.children;
  90621. for (var j = 0; j < children.length; j++) {
  90622. var child = null;
  90623. for (var k = 0; k < nodesToRoot.length; k++) {
  90624. if (nodesToRoot[k].id === children[j]) {
  90625. child = nodesToRoot[k];
  90626. break;
  90627. }
  90628. }
  90629. if (child) {
  90630. child.bone._parent = nodeToRoot.bone;
  90631. nodeToRoot.bone.children.push(child.bone);
  90632. }
  90633. }
  90634. }
  90635. };
  90636. /**
  90637. * Imports a skeleton
  90638. */
  90639. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90640. if (!newSkeleton) {
  90641. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90642. }
  90643. if (!skins.babylonSkeleton) {
  90644. return newSkeleton;
  90645. }
  90646. // Find the root bones
  90647. var nodesToRoot = [];
  90648. var nodesToRootToAdd = [];
  90649. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90650. newSkeleton.bones = [];
  90651. // Joints
  90652. for (var i = 0; i < skins.jointNames.length; i++) {
  90653. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90654. if (!jointNode) {
  90655. continue;
  90656. }
  90657. var node = jointNode.node;
  90658. if (!node) {
  90659. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90660. continue;
  90661. }
  90662. var id = jointNode.id;
  90663. // Optimize, if the bone already exists...
  90664. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90665. if (existingBone) {
  90666. newSkeleton.bones.push(existingBone);
  90667. continue;
  90668. }
  90669. // Search for parent bone
  90670. var foundBone = false;
  90671. var parentBone = null;
  90672. for (var j = 0; j < i; j++) {
  90673. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90674. if (!jointNode_1) {
  90675. continue;
  90676. }
  90677. var joint = jointNode_1.node;
  90678. if (!joint) {
  90679. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90680. continue;
  90681. }
  90682. var children = joint.children;
  90683. if (!children) {
  90684. continue;
  90685. }
  90686. foundBone = false;
  90687. for (var k = 0; k < children.length; k++) {
  90688. if (children[k] === id) {
  90689. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90690. foundBone = true;
  90691. break;
  90692. }
  90693. }
  90694. if (foundBone) {
  90695. break;
  90696. }
  90697. }
  90698. // Create bone
  90699. var mat = configureBoneTransformation(node);
  90700. if (!parentBone && nodesToRoot.length > 0) {
  90701. parentBone = getNodeToRoot(nodesToRoot, id);
  90702. if (parentBone) {
  90703. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90704. nodesToRootToAdd.push(parentBone);
  90705. }
  90706. }
  90707. }
  90708. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90709. bone.id = id;
  90710. }
  90711. // Polish
  90712. var bones = newSkeleton.bones;
  90713. newSkeleton.bones = [];
  90714. for (var i = 0; i < skins.jointNames.length; i++) {
  90715. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90716. if (!jointNode) {
  90717. continue;
  90718. }
  90719. for (var j = 0; j < bones.length; j++) {
  90720. if (bones[j].id === jointNode.id) {
  90721. newSkeleton.bones.push(bones[j]);
  90722. break;
  90723. }
  90724. }
  90725. }
  90726. newSkeleton.prepare();
  90727. // Finish
  90728. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90729. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90730. }
  90731. return newSkeleton;
  90732. };
  90733. /**
  90734. * Imports a mesh and its geometries
  90735. */
  90736. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90737. if (!newMesh) {
  90738. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90739. newMesh.id = id;
  90740. }
  90741. if (!node.babylonNode) {
  90742. return newMesh;
  90743. }
  90744. var subMaterials = [];
  90745. var vertexData = null;
  90746. var verticesStarts = new Array();
  90747. var verticesCounts = new Array();
  90748. var indexStarts = new Array();
  90749. var indexCounts = new Array();
  90750. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90751. var meshID = meshes[meshIndex];
  90752. var mesh = gltfRuntime.meshes[meshID];
  90753. if (!mesh) {
  90754. continue;
  90755. }
  90756. // Positions, normals and UVs
  90757. for (var i = 0; i < mesh.primitives.length; i++) {
  90758. // Temporary vertex data
  90759. var tempVertexData = new BABYLON.VertexData();
  90760. var primitive = mesh.primitives[i];
  90761. if (primitive.mode !== 4) {
  90762. // continue;
  90763. }
  90764. var attributes = primitive.attributes;
  90765. var accessor = null;
  90766. var buffer = null;
  90767. // Set positions, normal and uvs
  90768. for (var semantic in attributes) {
  90769. // Link accessor and buffer view
  90770. accessor = gltfRuntime.accessors[attributes[semantic]];
  90771. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90772. if (semantic === "NORMAL") {
  90773. tempVertexData.normals = new Float32Array(buffer.length);
  90774. tempVertexData.normals.set(buffer);
  90775. }
  90776. else if (semantic === "POSITION") {
  90777. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90778. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90779. for (var j = 0; j < buffer.length; j += 4) {
  90780. tempVertexData.positions[j] = buffer[j];
  90781. tempVertexData.positions[j + 1] = buffer[j + 1];
  90782. tempVertexData.positions[j + 2] = buffer[j + 2];
  90783. }
  90784. }
  90785. else {
  90786. tempVertexData.positions = new Float32Array(buffer.length);
  90787. tempVertexData.positions.set(buffer);
  90788. }
  90789. verticesCounts.push(tempVertexData.positions.length);
  90790. }
  90791. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90792. var channel = Number(semantic.split("_")[1]);
  90793. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90794. var uvs = new Float32Array(buffer.length);
  90795. uvs.set(buffer);
  90796. normalizeUVs(uvs);
  90797. tempVertexData.set(uvs, uvKind);
  90798. }
  90799. else if (semantic === "JOINT") {
  90800. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90801. tempVertexData.matricesIndices.set(buffer);
  90802. }
  90803. else if (semantic === "WEIGHT") {
  90804. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90805. tempVertexData.matricesWeights.set(buffer);
  90806. }
  90807. else if (semantic === "COLOR") {
  90808. tempVertexData.colors = new Float32Array(buffer.length);
  90809. tempVertexData.colors.set(buffer);
  90810. }
  90811. }
  90812. // Indices
  90813. accessor = gltfRuntime.accessors[primitive.indices];
  90814. if (accessor) {
  90815. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90816. tempVertexData.indices = new Int32Array(buffer.length);
  90817. tempVertexData.indices.set(buffer);
  90818. indexCounts.push(tempVertexData.indices.length);
  90819. }
  90820. else {
  90821. // Set indices on the fly
  90822. var indices = [];
  90823. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90824. indices.push(j);
  90825. }
  90826. tempVertexData.indices = new Int32Array(indices);
  90827. indexCounts.push(tempVertexData.indices.length);
  90828. }
  90829. if (!vertexData) {
  90830. vertexData = tempVertexData;
  90831. }
  90832. else {
  90833. vertexData.merge(tempVertexData);
  90834. }
  90835. // Sub material
  90836. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90837. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90838. // Update vertices start and index start
  90839. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90840. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90841. }
  90842. }
  90843. var material;
  90844. if (subMaterials.length > 1) {
  90845. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90846. material.subMaterials = subMaterials;
  90847. }
  90848. else {
  90849. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90850. }
  90851. if (subMaterials.length === 1) {
  90852. material = subMaterials[0];
  90853. }
  90854. if (!newMesh.material) {
  90855. newMesh.material = material;
  90856. }
  90857. // Apply geometry
  90858. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90859. newMesh.computeWorldMatrix(true);
  90860. // Apply submeshes
  90861. newMesh.subMeshes = [];
  90862. var index = 0;
  90863. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90864. var meshID = meshes[meshIndex];
  90865. var mesh = gltfRuntime.meshes[meshID];
  90866. if (!mesh) {
  90867. continue;
  90868. }
  90869. for (var i = 0; i < mesh.primitives.length; i++) {
  90870. if (mesh.primitives[i].mode !== 4) {
  90871. //continue;
  90872. }
  90873. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90874. index++;
  90875. }
  90876. }
  90877. // Finish
  90878. return newMesh;
  90879. };
  90880. /**
  90881. * Configure node transformation from position, rotation and scaling
  90882. */
  90883. var configureNode = function (newNode, position, rotation, scaling) {
  90884. if (newNode.position) {
  90885. newNode.position = position;
  90886. }
  90887. if (newNode.rotationQuaternion || newNode.rotation) {
  90888. newNode.rotationQuaternion = rotation;
  90889. }
  90890. if (newNode.scaling) {
  90891. newNode.scaling = scaling;
  90892. }
  90893. };
  90894. /**
  90895. * Configures node from transformation matrix
  90896. */
  90897. var configureNodeFromMatrix = function (newNode, node, parent) {
  90898. if (node.matrix) {
  90899. var position = new BABYLON.Vector3(0, 0, 0);
  90900. var rotation = new BABYLON.Quaternion();
  90901. var scaling = new BABYLON.Vector3(0, 0, 0);
  90902. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90903. mat.decompose(scaling, rotation, position);
  90904. configureNode(newNode, position, rotation, scaling);
  90905. }
  90906. else if (node.translation && node.rotation && node.scale) {
  90907. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90908. }
  90909. newNode.computeWorldMatrix(true);
  90910. };
  90911. /**
  90912. * Imports a node
  90913. */
  90914. var importNode = function (gltfRuntime, node, id, parent) {
  90915. var lastNode = null;
  90916. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90917. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90918. return null;
  90919. }
  90920. }
  90921. // Meshes
  90922. if (node.skin) {
  90923. if (node.meshes) {
  90924. var skin = gltfRuntime.skins[node.skin];
  90925. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90926. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90927. if (newMesh.skeleton === null) {
  90928. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90929. if (!skin.babylonSkeleton) {
  90930. skin.babylonSkeleton = newMesh.skeleton;
  90931. }
  90932. }
  90933. lastNode = newMesh;
  90934. }
  90935. }
  90936. else if (node.meshes) {
  90937. /**
  90938. * Improve meshes property
  90939. */
  90940. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90941. lastNode = newMesh;
  90942. }
  90943. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90944. var light = gltfRuntime.lights[node.light];
  90945. if (light) {
  90946. if (light.type === "ambient") {
  90947. var ambienLight = light[light.type];
  90948. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90949. hemiLight.name = node.name || "";
  90950. if (ambienLight.color) {
  90951. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  90952. }
  90953. lastNode = hemiLight;
  90954. }
  90955. else if (light.type === "directional") {
  90956. var directionalLight = light[light.type];
  90957. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90958. dirLight.name = node.name || "";
  90959. if (directionalLight.color) {
  90960. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  90961. }
  90962. lastNode = dirLight;
  90963. }
  90964. else if (light.type === "point") {
  90965. var pointLight = light[light.type];
  90966. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90967. ptLight.name = node.name || "";
  90968. if (pointLight.color) {
  90969. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  90970. }
  90971. lastNode = ptLight;
  90972. }
  90973. else if (light.type === "spot") {
  90974. var spotLight = light[light.type];
  90975. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  90976. spLight.name = node.name || "";
  90977. if (spotLight.color) {
  90978. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  90979. }
  90980. if (spotLight.fallOfAngle) {
  90981. spLight.angle = spotLight.fallOfAngle;
  90982. }
  90983. if (spotLight.fallOffExponent) {
  90984. spLight.exponent = spotLight.fallOffExponent;
  90985. }
  90986. lastNode = spLight;
  90987. }
  90988. }
  90989. }
  90990. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90991. var camera = gltfRuntime.cameras[node.camera];
  90992. if (camera) {
  90993. if (camera.type === "orthographic") {
  90994. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90995. orthoCamera.name = node.name || "";
  90996. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  90997. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90998. lastNode = orthoCamera;
  90999. }
  91000. else if (camera.type === "perspective") {
  91001. var perspectiveCamera = camera[camera.type];
  91002. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91003. persCamera.name = node.name || "";
  91004. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91005. if (!perspectiveCamera.aspectRatio) {
  91006. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91007. }
  91008. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91009. persCamera.maxZ = perspectiveCamera.zfar;
  91010. persCamera.minZ = perspectiveCamera.znear;
  91011. }
  91012. lastNode = persCamera;
  91013. }
  91014. }
  91015. }
  91016. // Empty node
  91017. if (!node.jointName) {
  91018. if (node.babylonNode) {
  91019. return node.babylonNode;
  91020. }
  91021. else if (lastNode === null) {
  91022. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91023. node.babylonNode = dummy;
  91024. lastNode = dummy;
  91025. }
  91026. }
  91027. if (lastNode !== null) {
  91028. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91029. configureNodeFromMatrix(lastNode, node, parent);
  91030. }
  91031. else {
  91032. var translation = node.translation || [0, 0, 0];
  91033. var rotation = node.rotation || [0, 0, 0, 1];
  91034. var scale = node.scale || [1, 1, 1];
  91035. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91036. }
  91037. lastNode.updateCache(true);
  91038. node.babylonNode = lastNode;
  91039. }
  91040. return lastNode;
  91041. };
  91042. /**
  91043. * Traverses nodes and creates them
  91044. */
  91045. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91046. if (meshIncluded === void 0) { meshIncluded = false; }
  91047. var node = gltfRuntime.nodes[id];
  91048. var newNode = null;
  91049. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91050. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91051. meshIncluded = true;
  91052. }
  91053. else {
  91054. meshIncluded = false;
  91055. }
  91056. }
  91057. else {
  91058. meshIncluded = true;
  91059. }
  91060. if (!node.jointName && meshIncluded) {
  91061. newNode = importNode(gltfRuntime, node, id, parent);
  91062. if (newNode !== null) {
  91063. newNode.id = id;
  91064. newNode.parent = parent;
  91065. }
  91066. }
  91067. if (node.children) {
  91068. for (var i = 0; i < node.children.length; i++) {
  91069. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91070. }
  91071. }
  91072. };
  91073. /**
  91074. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91075. */
  91076. var postLoad = function (gltfRuntime) {
  91077. // Nodes
  91078. var currentScene = gltfRuntime.currentScene;
  91079. if (currentScene) {
  91080. for (var i = 0; i < currentScene.nodes.length; i++) {
  91081. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91082. }
  91083. }
  91084. else {
  91085. for (var thing in gltfRuntime.scenes) {
  91086. currentScene = gltfRuntime.scenes[thing];
  91087. for (var i = 0; i < currentScene.nodes.length; i++) {
  91088. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91089. }
  91090. }
  91091. }
  91092. // Set animations
  91093. loadAnimations(gltfRuntime);
  91094. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91095. var skeleton = gltfRuntime.scene.skeletons[i];
  91096. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91097. }
  91098. };
  91099. /**
  91100. * onBind shaderrs callback to set uniforms and matrices
  91101. */
  91102. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91103. var materialValues = material.values || technique.parameters;
  91104. for (var unif in unTreatedUniforms) {
  91105. var uniform = unTreatedUniforms[unif];
  91106. var type = uniform.type;
  91107. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91108. if (uniform.semantic && !uniform.source && !uniform.node) {
  91109. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91110. }
  91111. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91112. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91113. if (source === null) {
  91114. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91115. }
  91116. if (source === null) {
  91117. continue;
  91118. }
  91119. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91120. }
  91121. }
  91122. else {
  91123. var value = materialValues[technique.uniforms[unif]];
  91124. if (!value) {
  91125. continue;
  91126. }
  91127. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91128. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91129. if (texture === null || texture === undefined) {
  91130. continue;
  91131. }
  91132. shaderMaterial.getEffect().setTexture(unif, texture);
  91133. }
  91134. else {
  91135. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91136. }
  91137. }
  91138. }
  91139. onSuccess(shaderMaterial);
  91140. };
  91141. /**
  91142. * Prepare uniforms to send the only one time
  91143. * Loads the appropriate textures
  91144. */
  91145. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91146. var materialValues = material.values || technique.parameters;
  91147. var techniqueUniforms = technique.uniforms;
  91148. /**
  91149. * Prepare values here (not matrices)
  91150. */
  91151. for (var unif in unTreatedUniforms) {
  91152. var uniform = unTreatedUniforms[unif];
  91153. var type = uniform.type;
  91154. var value = materialValues[techniqueUniforms[unif]];
  91155. if (value === undefined) {
  91156. // In case the value is the same for all materials
  91157. value = uniform.value;
  91158. }
  91159. if (!value) {
  91160. continue;
  91161. }
  91162. var onLoadTexture = function (uniformName) {
  91163. return function (texture) {
  91164. if (uniform.value && uniformName) {
  91165. // Static uniform
  91166. shaderMaterial.setTexture(uniformName, texture);
  91167. delete unTreatedUniforms[uniformName];
  91168. }
  91169. };
  91170. };
  91171. // Texture (sampler2D)
  91172. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91173. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91174. }
  91175. else {
  91176. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91177. // Static uniform
  91178. delete unTreatedUniforms[unif];
  91179. }
  91180. }
  91181. }
  91182. };
  91183. /**
  91184. * Shader compilation failed
  91185. */
  91186. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91187. return function (effect, error) {
  91188. shaderMaterial.dispose(true);
  91189. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91190. };
  91191. };
  91192. /**
  91193. * Shader compilation success
  91194. */
  91195. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91196. return function (_) {
  91197. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91198. shaderMaterial.onBind = function (mesh) {
  91199. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91200. };
  91201. };
  91202. };
  91203. /**
  91204. * Returns the appropriate uniform if already handled by babylon
  91205. */
  91206. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91207. for (var unif in technique.uniforms) {
  91208. var uniform = technique.uniforms[unif];
  91209. var uniformParameter = technique.parameters[uniform];
  91210. if (tokenizer.currentIdentifier === unif) {
  91211. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91212. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91213. if (transformIndex !== -1) {
  91214. delete unTreatedUniforms[unif];
  91215. return babylonTransforms[transformIndex];
  91216. }
  91217. }
  91218. }
  91219. }
  91220. return tokenizer.currentIdentifier;
  91221. };
  91222. /**
  91223. * All shaders loaded. Create materials one by one
  91224. */
  91225. var importMaterials = function (gltfRuntime) {
  91226. // Create materials
  91227. for (var mat in gltfRuntime.materials) {
  91228. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91229. }
  91230. };
  91231. /**
  91232. * Implementation of the base glTF spec
  91233. */
  91234. var GLTFLoaderBase = /** @class */ (function () {
  91235. function GLTFLoaderBase() {
  91236. }
  91237. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91238. var gltfRuntime = {
  91239. extensions: {},
  91240. accessors: {},
  91241. buffers: {},
  91242. bufferViews: {},
  91243. meshes: {},
  91244. lights: {},
  91245. cameras: {},
  91246. nodes: {},
  91247. images: {},
  91248. textures: {},
  91249. shaders: {},
  91250. programs: {},
  91251. samplers: {},
  91252. techniques: {},
  91253. materials: {},
  91254. animations: {},
  91255. skins: {},
  91256. extensionsUsed: [],
  91257. scenes: {},
  91258. buffersCount: 0,
  91259. shaderscount: 0,
  91260. scene: scene,
  91261. rootUrl: rootUrl,
  91262. loadedBufferCount: 0,
  91263. loadedBufferViews: {},
  91264. loadedShaderCount: 0,
  91265. importOnlyMeshes: false,
  91266. dummyNodes: []
  91267. };
  91268. // Parse
  91269. if (parsedData.extensions) {
  91270. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91271. }
  91272. if (parsedData.extensionsUsed) {
  91273. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91274. }
  91275. if (parsedData.buffers) {
  91276. parseBuffers(parsedData.buffers, gltfRuntime);
  91277. }
  91278. if (parsedData.bufferViews) {
  91279. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91280. }
  91281. if (parsedData.accessors) {
  91282. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91283. }
  91284. if (parsedData.meshes) {
  91285. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91286. }
  91287. if (parsedData.lights) {
  91288. parseObject(parsedData.lights, "lights", gltfRuntime);
  91289. }
  91290. if (parsedData.cameras) {
  91291. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91292. }
  91293. if (parsedData.nodes) {
  91294. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91295. }
  91296. if (parsedData.images) {
  91297. parseObject(parsedData.images, "images", gltfRuntime);
  91298. }
  91299. if (parsedData.textures) {
  91300. parseObject(parsedData.textures, "textures", gltfRuntime);
  91301. }
  91302. if (parsedData.shaders) {
  91303. parseShaders(parsedData.shaders, gltfRuntime);
  91304. }
  91305. if (parsedData.programs) {
  91306. parseObject(parsedData.programs, "programs", gltfRuntime);
  91307. }
  91308. if (parsedData.samplers) {
  91309. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91310. }
  91311. if (parsedData.techniques) {
  91312. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91313. }
  91314. if (parsedData.materials) {
  91315. parseObject(parsedData.materials, "materials", gltfRuntime);
  91316. }
  91317. if (parsedData.animations) {
  91318. parseObject(parsedData.animations, "animations", gltfRuntime);
  91319. }
  91320. if (parsedData.skins) {
  91321. parseObject(parsedData.skins, "skins", gltfRuntime);
  91322. }
  91323. if (parsedData.scenes) {
  91324. gltfRuntime.scenes = parsedData.scenes;
  91325. }
  91326. if (parsedData.scene && parsedData.scenes) {
  91327. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91328. }
  91329. return gltfRuntime;
  91330. };
  91331. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91332. var buffer = gltfRuntime.buffers[id];
  91333. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91334. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91335. }
  91336. else {
  91337. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91338. if (request) {
  91339. onError(request.status + " " + request.statusText);
  91340. }
  91341. });
  91342. }
  91343. };
  91344. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91345. var texture = gltfRuntime.textures[id];
  91346. if (!texture || !texture.source) {
  91347. onError("");
  91348. return;
  91349. }
  91350. if (texture.babylonTexture) {
  91351. onSuccess(null);
  91352. return;
  91353. }
  91354. var source = gltfRuntime.images[texture.source];
  91355. if (BABYLON.Tools.IsBase64(source.uri)) {
  91356. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91357. }
  91358. else {
  91359. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91360. if (request) {
  91361. onError(request.status + " " + request.statusText);
  91362. }
  91363. });
  91364. }
  91365. };
  91366. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91367. var texture = gltfRuntime.textures[id];
  91368. if (texture.babylonTexture) {
  91369. onSuccess(texture.babylonTexture);
  91370. return;
  91371. }
  91372. var sampler = gltfRuntime.samplers[texture.sampler];
  91373. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91374. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91375. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91376. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91377. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91378. var blob = new Blob([buffer]);
  91379. var blobURL = URL.createObjectURL(blob);
  91380. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91381. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91382. if (sampler.wrapS !== undefined) {
  91383. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91384. }
  91385. if (sampler.wrapT !== undefined) {
  91386. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91387. }
  91388. newTexture.name = id;
  91389. texture.babylonTexture = newTexture;
  91390. onSuccess(newTexture);
  91391. };
  91392. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91393. var shader = gltfRuntime.shaders[id];
  91394. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91395. var shaderString = atob(shader.uri.split(",")[1]);
  91396. onSuccess(shaderString);
  91397. }
  91398. else {
  91399. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91400. if (request) {
  91401. onError(request.status + " " + request.statusText);
  91402. }
  91403. });
  91404. }
  91405. };
  91406. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91407. var material = gltfRuntime.materials[id];
  91408. if (!material.technique) {
  91409. if (onError) {
  91410. onError("No technique found.");
  91411. }
  91412. return;
  91413. }
  91414. var technique = gltfRuntime.techniques[material.technique];
  91415. if (!technique) {
  91416. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91417. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91418. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91419. onSuccess(defaultMaterial);
  91420. return;
  91421. }
  91422. var program = gltfRuntime.programs[technique.program];
  91423. var states = technique.states;
  91424. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91425. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91426. var newVertexShader = "";
  91427. var newPixelShader = "";
  91428. var vertexTokenizer = new Tokenizer(vertexShader);
  91429. var pixelTokenizer = new Tokenizer(pixelShader);
  91430. var unTreatedUniforms = {};
  91431. var uniforms = [];
  91432. var attributes = [];
  91433. var samplers = [];
  91434. // Fill uniform, sampler2D and attributes
  91435. for (var unif in technique.uniforms) {
  91436. var uniform = technique.uniforms[unif];
  91437. var uniformParameter = technique.parameters[uniform];
  91438. unTreatedUniforms[unif] = uniformParameter;
  91439. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91440. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91441. if (transformIndex !== -1) {
  91442. uniforms.push(babylonTransforms[transformIndex]);
  91443. delete unTreatedUniforms[unif];
  91444. }
  91445. else {
  91446. uniforms.push(unif);
  91447. }
  91448. }
  91449. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91450. samplers.push(unif);
  91451. }
  91452. else {
  91453. uniforms.push(unif);
  91454. }
  91455. }
  91456. for (var attr in technique.attributes) {
  91457. var attribute = technique.attributes[attr];
  91458. var attributeParameter = technique.parameters[attribute];
  91459. if (attributeParameter.semantic) {
  91460. attributes.push(getAttribute(attributeParameter));
  91461. }
  91462. }
  91463. // Configure vertex shader
  91464. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91465. var tokenType = vertexTokenizer.currentToken;
  91466. if (tokenType !== ETokenType.IDENTIFIER) {
  91467. newVertexShader += vertexTokenizer.currentString;
  91468. continue;
  91469. }
  91470. var foundAttribute = false;
  91471. for (var attr in technique.attributes) {
  91472. var attribute = technique.attributes[attr];
  91473. var attributeParameter = technique.parameters[attribute];
  91474. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91475. newVertexShader += getAttribute(attributeParameter);
  91476. foundAttribute = true;
  91477. break;
  91478. }
  91479. }
  91480. if (foundAttribute) {
  91481. continue;
  91482. }
  91483. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91484. }
  91485. // Configure pixel shader
  91486. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91487. var tokenType = pixelTokenizer.currentToken;
  91488. if (tokenType !== ETokenType.IDENTIFIER) {
  91489. newPixelShader += pixelTokenizer.currentString;
  91490. continue;
  91491. }
  91492. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91493. }
  91494. // Create shader material
  91495. var shaderPath = {
  91496. vertex: program.vertexShader + id,
  91497. fragment: program.fragmentShader + id
  91498. };
  91499. var options = {
  91500. attributes: attributes,
  91501. uniforms: uniforms,
  91502. samplers: samplers,
  91503. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91504. };
  91505. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91506. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91507. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91508. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91509. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91510. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91511. if (states && states.functions) {
  91512. var functions = states.functions;
  91513. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91514. shaderMaterial.backFaceCulling = false;
  91515. }
  91516. var blendFunc = functions.blendFuncSeparate;
  91517. if (blendFunc) {
  91518. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91519. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91520. }
  91521. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91522. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91523. }
  91524. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91525. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91526. }
  91527. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91528. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91529. }
  91530. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91531. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91532. }
  91533. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91534. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91535. }
  91536. }
  91537. }
  91538. };
  91539. return GLTFLoaderBase;
  91540. }());
  91541. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91542. /**
  91543. * glTF V1 Loader
  91544. */
  91545. var GLTFLoader = /** @class */ (function () {
  91546. function GLTFLoader() {
  91547. // #region Stubs for IGLTFLoader interface
  91548. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91549. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91550. this.compileMaterials = false;
  91551. this.useClipPlane = false;
  91552. this.compileShadowGenerators = false;
  91553. this.onDisposeObservable = new BABYLON.Observable();
  91554. this.onMeshLoadedObservable = new BABYLON.Observable();
  91555. this.onTextureLoadedObservable = new BABYLON.Observable();
  91556. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91557. this.onCompleteObservable = new BABYLON.Observable();
  91558. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91559. this.state = null;
  91560. }
  91561. GLTFLoader.RegisterExtension = function (extension) {
  91562. if (GLTFLoader.Extensions[extension.name]) {
  91563. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91564. return;
  91565. }
  91566. GLTFLoader.Extensions[extension.name] = extension;
  91567. };
  91568. GLTFLoader.prototype.dispose = function () { };
  91569. // #endregion
  91570. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91571. var _this = this;
  91572. scene.useRightHandedSystem = true;
  91573. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91574. gltfRuntime.importOnlyMeshes = true;
  91575. if (meshesNames === "") {
  91576. gltfRuntime.importMeshesNames = [];
  91577. }
  91578. else if (typeof meshesNames === "string") {
  91579. gltfRuntime.importMeshesNames = [meshesNames];
  91580. }
  91581. else if (meshesNames && !(meshesNames instanceof Array)) {
  91582. gltfRuntime.importMeshesNames = [meshesNames];
  91583. }
  91584. else {
  91585. gltfRuntime.importMeshesNames = [];
  91586. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91587. }
  91588. // Create nodes
  91589. _this._createNodes(gltfRuntime);
  91590. var meshes = new Array();
  91591. var skeletons = new Array();
  91592. // Fill arrays of meshes and skeletons
  91593. for (var nde in gltfRuntime.nodes) {
  91594. var node = gltfRuntime.nodes[nde];
  91595. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91596. meshes.push(node.babylonNode);
  91597. }
  91598. }
  91599. for (var skl in gltfRuntime.skins) {
  91600. var skin = gltfRuntime.skins[skl];
  91601. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91602. skeletons.push(skin.babylonSkeleton);
  91603. }
  91604. }
  91605. // Load buffers, shaders, materials, etc.
  91606. _this._loadBuffersAsync(gltfRuntime, function () {
  91607. _this._loadShadersAsync(gltfRuntime, function () {
  91608. importMaterials(gltfRuntime);
  91609. postLoad(gltfRuntime);
  91610. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91611. onSuccess(meshes, [], skeletons);
  91612. }
  91613. });
  91614. }, onProgress);
  91615. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91616. onSuccess(meshes, [], skeletons);
  91617. }
  91618. }, onError);
  91619. return true;
  91620. };
  91621. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91622. var _this = this;
  91623. return new Promise(function (resolve, reject) {
  91624. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91625. resolve({
  91626. meshes: meshes,
  91627. particleSystems: particleSystems,
  91628. skeletons: skeletons
  91629. });
  91630. }, onProgress, function (message) {
  91631. reject(new Error(message));
  91632. });
  91633. });
  91634. };
  91635. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91636. var _this = this;
  91637. scene.useRightHandedSystem = true;
  91638. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91639. // Load runtime extensios
  91640. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91641. // Create nodes
  91642. _this._createNodes(gltfRuntime);
  91643. // Load buffers, shaders, materials, etc.
  91644. _this._loadBuffersAsync(gltfRuntime, function () {
  91645. _this._loadShadersAsync(gltfRuntime, function () {
  91646. importMaterials(gltfRuntime);
  91647. postLoad(gltfRuntime);
  91648. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91649. onSuccess();
  91650. }
  91651. });
  91652. });
  91653. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91654. onSuccess();
  91655. }
  91656. }, onError);
  91657. }, onError);
  91658. };
  91659. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91660. var _this = this;
  91661. return new Promise(function (resolve, reject) {
  91662. _this._loadAsync(scene, data, rootUrl, function () {
  91663. resolve();
  91664. }, onProgress, function (message) {
  91665. reject(new Error(message));
  91666. });
  91667. });
  91668. };
  91669. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91670. var hasShaders = false;
  91671. var processShader = function (sha, shader) {
  91672. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91673. gltfRuntime.loadedShaderCount++;
  91674. if (shaderString) {
  91675. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91676. }
  91677. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91678. onload();
  91679. }
  91680. }, function () {
  91681. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91682. });
  91683. };
  91684. for (var sha in gltfRuntime.shaders) {
  91685. hasShaders = true;
  91686. var shader = gltfRuntime.shaders[sha];
  91687. if (shader) {
  91688. processShader.bind(this, sha, shader)();
  91689. }
  91690. else {
  91691. BABYLON.Tools.Error("No shader named: " + sha);
  91692. }
  91693. }
  91694. if (!hasShaders) {
  91695. onload();
  91696. }
  91697. };
  91698. ;
  91699. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91700. var hasBuffers = false;
  91701. var processBuffer = function (buf, buffer) {
  91702. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91703. gltfRuntime.loadedBufferCount++;
  91704. if (bufferView) {
  91705. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91706. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91707. }
  91708. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91709. }
  91710. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91711. onLoad();
  91712. }
  91713. }, function () {
  91714. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91715. });
  91716. };
  91717. for (var buf in gltfRuntime.buffers) {
  91718. hasBuffers = true;
  91719. var buffer = gltfRuntime.buffers[buf];
  91720. if (buffer) {
  91721. processBuffer.bind(this, buf, buffer)();
  91722. }
  91723. else {
  91724. BABYLON.Tools.Error("No buffer named: " + buf);
  91725. }
  91726. }
  91727. if (!hasBuffers) {
  91728. onLoad();
  91729. }
  91730. };
  91731. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91732. var currentScene = gltfRuntime.currentScene;
  91733. if (currentScene) {
  91734. // Only one scene even if multiple scenes are defined
  91735. for (var i = 0; i < currentScene.nodes.length; i++) {
  91736. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91737. }
  91738. }
  91739. else {
  91740. // Load all scenes
  91741. for (var thing in gltfRuntime.scenes) {
  91742. currentScene = gltfRuntime.scenes[thing];
  91743. for (var i = 0; i < currentScene.nodes.length; i++) {
  91744. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91745. }
  91746. }
  91747. }
  91748. };
  91749. GLTFLoader.Extensions = {};
  91750. return GLTFLoader;
  91751. }());
  91752. GLTF1.GLTFLoader = GLTFLoader;
  91753. ;
  91754. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91755. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91756. })(BABYLON || (BABYLON = {}));
  91757. //# sourceMappingURL=babylon.glTFLoader.js.map
  91758. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91759. var BABYLON;
  91760. (function (BABYLON) {
  91761. var GLTF1;
  91762. (function (GLTF1) {
  91763. /**
  91764. * Utils functions for GLTF
  91765. */
  91766. var GLTFUtils = /** @class */ (function () {
  91767. function GLTFUtils() {
  91768. }
  91769. /**
  91770. * Sets the given "parameter" matrix
  91771. * @param scene: the {BABYLON.Scene} object
  91772. * @param source: the source node where to pick the matrix
  91773. * @param parameter: the GLTF technique parameter
  91774. * @param uniformName: the name of the shader's uniform
  91775. * @param shaderMaterial: the shader material
  91776. */
  91777. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91778. var mat = null;
  91779. if (parameter.semantic === "MODEL") {
  91780. mat = source.getWorldMatrix();
  91781. }
  91782. else if (parameter.semantic === "PROJECTION") {
  91783. mat = scene.getProjectionMatrix();
  91784. }
  91785. else if (parameter.semantic === "VIEW") {
  91786. mat = scene.getViewMatrix();
  91787. }
  91788. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91789. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91790. }
  91791. else if (parameter.semantic === "MODELVIEW") {
  91792. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91793. }
  91794. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91795. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91796. }
  91797. else if (parameter.semantic === "MODELINVERSE") {
  91798. mat = source.getWorldMatrix().invert();
  91799. }
  91800. else if (parameter.semantic === "VIEWINVERSE") {
  91801. mat = scene.getViewMatrix().invert();
  91802. }
  91803. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91804. mat = scene.getProjectionMatrix().invert();
  91805. }
  91806. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91807. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91808. }
  91809. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91810. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91811. }
  91812. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91813. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91814. }
  91815. else {
  91816. debugger;
  91817. }
  91818. if (mat) {
  91819. switch (parameter.type) {
  91820. case GLTF1.EParameterType.FLOAT_MAT2:
  91821. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91822. break;
  91823. case GLTF1.EParameterType.FLOAT_MAT3:
  91824. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91825. break;
  91826. case GLTF1.EParameterType.FLOAT_MAT4:
  91827. shaderMaterial.setMatrix(uniformName, mat);
  91828. break;
  91829. default: break;
  91830. }
  91831. }
  91832. };
  91833. /**
  91834. * Sets the given "parameter" matrix
  91835. * @param shaderMaterial: the shader material
  91836. * @param uniform: the name of the shader's uniform
  91837. * @param value: the value of the uniform
  91838. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91839. */
  91840. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91841. switch (type) {
  91842. case GLTF1.EParameterType.FLOAT:
  91843. shaderMaterial.setFloat(uniform, value);
  91844. return true;
  91845. case GLTF1.EParameterType.FLOAT_VEC2:
  91846. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91847. return true;
  91848. case GLTF1.EParameterType.FLOAT_VEC3:
  91849. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91850. return true;
  91851. case GLTF1.EParameterType.FLOAT_VEC4:
  91852. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91853. return true;
  91854. default: return false;
  91855. }
  91856. };
  91857. /**
  91858. * Returns the wrap mode of the texture
  91859. * @param mode: the mode value
  91860. */
  91861. GLTFUtils.GetWrapMode = function (mode) {
  91862. switch (mode) {
  91863. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91864. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91865. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91866. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91867. }
  91868. };
  91869. /**
  91870. * Returns the byte stride giving an accessor
  91871. * @param accessor: the GLTF accessor objet
  91872. */
  91873. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91874. // Needs this function since "byteStride" isn't requiered in glTF format
  91875. var type = accessor.type;
  91876. switch (type) {
  91877. case "VEC2": return 2;
  91878. case "VEC3": return 3;
  91879. case "VEC4": return 4;
  91880. case "MAT2": return 4;
  91881. case "MAT3": return 9;
  91882. case "MAT4": return 16;
  91883. default: return 1;
  91884. }
  91885. };
  91886. /**
  91887. * Returns the texture filter mode giving a mode value
  91888. * @param mode: the filter mode value
  91889. */
  91890. GLTFUtils.GetTextureFilterMode = function (mode) {
  91891. switch (mode) {
  91892. case GLTF1.ETextureFilterType.LINEAR:
  91893. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91894. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91895. case GLTF1.ETextureFilterType.NEAREST:
  91896. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91897. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91898. }
  91899. };
  91900. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91901. var byteOffset = bufferView.byteOffset + byteOffset;
  91902. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91903. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91904. throw new Error("Buffer access is out of range");
  91905. }
  91906. var buffer = loadedBufferView.buffer;
  91907. byteOffset += loadedBufferView.byteOffset;
  91908. switch (componentType) {
  91909. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91910. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91911. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91912. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91913. default: return new Float32Array(buffer, byteOffset, byteLength);
  91914. }
  91915. };
  91916. /**
  91917. * Returns a buffer from its accessor
  91918. * @param gltfRuntime: the GLTF runtime
  91919. * @param accessor: the GLTF accessor
  91920. */
  91921. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91922. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91923. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91924. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91925. };
  91926. /**
  91927. * Decodes a buffer view into a string
  91928. * @param view: the buffer view
  91929. */
  91930. GLTFUtils.DecodeBufferToText = function (view) {
  91931. var result = "";
  91932. var length = view.byteLength;
  91933. for (var i = 0; i < length; ++i) {
  91934. result += String.fromCharCode(view[i]);
  91935. }
  91936. return result;
  91937. };
  91938. /**
  91939. * Returns the default material of gltf. Related to
  91940. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91941. * @param scene: the Babylon.js scene
  91942. */
  91943. GLTFUtils.GetDefaultMaterial = function (scene) {
  91944. if (!GLTFUtils._DefaultMaterial) {
  91945. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  91946. "precision highp float;",
  91947. "",
  91948. "uniform mat4 worldView;",
  91949. "uniform mat4 projection;",
  91950. "",
  91951. "attribute vec3 position;",
  91952. "",
  91953. "void main(void)",
  91954. "{",
  91955. " gl_Position = projection * worldView * vec4(position, 1.0);",
  91956. "}"
  91957. ].join("\n");
  91958. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  91959. "precision highp float;",
  91960. "",
  91961. "uniform vec4 u_emission;",
  91962. "",
  91963. "void main(void)",
  91964. "{",
  91965. " gl_FragColor = u_emission;",
  91966. "}"
  91967. ].join("\n");
  91968. var shaderPath = {
  91969. vertex: "GLTFDefaultMaterial",
  91970. fragment: "GLTFDefaultMaterial"
  91971. };
  91972. var options = {
  91973. attributes: ["position"],
  91974. uniforms: ["worldView", "projection", "u_emission"],
  91975. samplers: new Array(),
  91976. needAlphaBlending: false
  91977. };
  91978. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  91979. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  91980. }
  91981. return GLTFUtils._DefaultMaterial;
  91982. };
  91983. // The GLTF default material
  91984. GLTFUtils._DefaultMaterial = null;
  91985. return GLTFUtils;
  91986. }());
  91987. GLTF1.GLTFUtils = GLTFUtils;
  91988. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91989. })(BABYLON || (BABYLON = {}));
  91990. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91991. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91992. var BABYLON;
  91993. (function (BABYLON) {
  91994. var GLTF1;
  91995. (function (GLTF1) {
  91996. var GLTFLoaderExtension = /** @class */ (function () {
  91997. function GLTFLoaderExtension(name) {
  91998. this._name = name;
  91999. }
  92000. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92001. get: function () {
  92002. return this._name;
  92003. },
  92004. enumerable: true,
  92005. configurable: true
  92006. });
  92007. /**
  92008. * Defines an override for loading the runtime
  92009. * Return true to stop further extensions from loading the runtime
  92010. */
  92011. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92012. return false;
  92013. };
  92014. /**
  92015. * Defines an onverride for creating gltf runtime
  92016. * Return true to stop further extensions from creating the runtime
  92017. */
  92018. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92019. return false;
  92020. };
  92021. /**
  92022. * Defines an override for loading buffers
  92023. * Return true to stop further extensions from loading this buffer
  92024. */
  92025. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92026. return false;
  92027. };
  92028. /**
  92029. * Defines an override for loading texture buffers
  92030. * Return true to stop further extensions from loading this texture data
  92031. */
  92032. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92033. return false;
  92034. };
  92035. /**
  92036. * Defines an override for creating textures
  92037. * Return true to stop further extensions from loading this texture
  92038. */
  92039. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92040. return false;
  92041. };
  92042. /**
  92043. * Defines an override for loading shader strings
  92044. * Return true to stop further extensions from loading this shader data
  92045. */
  92046. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92047. return false;
  92048. };
  92049. /**
  92050. * Defines an override for loading materials
  92051. * Return true to stop further extensions from loading this material
  92052. */
  92053. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92054. return false;
  92055. };
  92056. // ---------
  92057. // Utilities
  92058. // ---------
  92059. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92060. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92061. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92062. }, function () {
  92063. setTimeout(function () {
  92064. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92065. });
  92066. });
  92067. };
  92068. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92069. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92070. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92071. }, function () {
  92072. setTimeout(function () {
  92073. onSuccess();
  92074. });
  92075. });
  92076. };
  92077. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92078. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92079. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92080. }, function () {
  92081. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92082. });
  92083. };
  92084. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92085. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92086. };
  92087. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92088. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92089. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92090. }, function () {
  92091. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92092. });
  92093. };
  92094. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92095. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92096. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92097. }, function () {
  92098. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92099. });
  92100. };
  92101. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92102. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92103. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92104. }, function () {
  92105. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92106. });
  92107. };
  92108. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92109. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92110. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92111. }, function () {
  92112. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92113. });
  92114. };
  92115. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92116. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92117. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92118. if (func(loaderExtension)) {
  92119. return;
  92120. }
  92121. }
  92122. defaultFunc();
  92123. };
  92124. return GLTFLoaderExtension;
  92125. }());
  92126. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92127. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92128. })(BABYLON || (BABYLON = {}));
  92129. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92130. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92131. var BABYLON;
  92132. (function (BABYLON) {
  92133. var GLTF1;
  92134. (function (GLTF1) {
  92135. var BinaryExtensionBufferName = "binary_glTF";
  92136. ;
  92137. ;
  92138. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92139. __extends(GLTFBinaryExtension, _super);
  92140. function GLTFBinaryExtension() {
  92141. return _super.call(this, "KHR_binary_glTF") || this;
  92142. }
  92143. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92144. var extensionsUsed = data.json.extensionsUsed;
  92145. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92146. return false;
  92147. }
  92148. this._bin = data.bin;
  92149. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92150. return true;
  92151. };
  92152. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92153. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92154. return false;
  92155. }
  92156. if (id !== BinaryExtensionBufferName) {
  92157. return false;
  92158. }
  92159. onSuccess(this._bin);
  92160. return true;
  92161. };
  92162. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92163. var texture = gltfRuntime.textures[id];
  92164. var source = gltfRuntime.images[texture.source];
  92165. if (!source.extensions || !(this.name in source.extensions)) {
  92166. return false;
  92167. }
  92168. var sourceExt = source.extensions[this.name];
  92169. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92170. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92171. onSuccess(buffer);
  92172. return true;
  92173. };
  92174. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92175. var shader = gltfRuntime.shaders[id];
  92176. if (!shader.extensions || !(this.name in shader.extensions)) {
  92177. return false;
  92178. }
  92179. var binaryExtensionShader = shader.extensions[this.name];
  92180. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92181. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92182. setTimeout(function () {
  92183. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92184. onSuccess(shaderString);
  92185. });
  92186. return true;
  92187. };
  92188. return GLTFBinaryExtension;
  92189. }(GLTF1.GLTFLoaderExtension));
  92190. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92191. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92192. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92193. })(BABYLON || (BABYLON = {}));
  92194. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92195. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92196. var BABYLON;
  92197. (function (BABYLON) {
  92198. var GLTF1;
  92199. (function (GLTF1) {
  92200. ;
  92201. ;
  92202. ;
  92203. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92204. __extends(GLTFMaterialsCommonExtension, _super);
  92205. function GLTFMaterialsCommonExtension() {
  92206. return _super.call(this, "KHR_materials_common") || this;
  92207. }
  92208. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92209. if (!gltfRuntime.extensions)
  92210. return false;
  92211. var extension = gltfRuntime.extensions[this.name];
  92212. if (!extension)
  92213. return false;
  92214. // Create lights
  92215. var lights = extension.lights;
  92216. if (lights) {
  92217. for (var thing in lights) {
  92218. var light = lights[thing];
  92219. switch (light.type) {
  92220. case "ambient":
  92221. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92222. var ambient = light.ambient;
  92223. if (ambient) {
  92224. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92225. }
  92226. break;
  92227. case "point":
  92228. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92229. var point = light.point;
  92230. if (point) {
  92231. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92232. }
  92233. break;
  92234. case "directional":
  92235. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92236. var directional = light.directional;
  92237. if (directional) {
  92238. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92239. }
  92240. break;
  92241. case "spot":
  92242. var spot = light.spot;
  92243. if (spot) {
  92244. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  92245. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92246. }
  92247. break;
  92248. default:
  92249. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92250. break;
  92251. }
  92252. }
  92253. }
  92254. return false;
  92255. };
  92256. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92257. var material = gltfRuntime.materials[id];
  92258. if (!material || !material.extensions)
  92259. return false;
  92260. var extension = material.extensions[this.name];
  92261. if (!extension)
  92262. return false;
  92263. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92264. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92265. if (extension.technique === "CONSTANT") {
  92266. standardMaterial.disableLighting = true;
  92267. }
  92268. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92269. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92270. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92271. // Ambient
  92272. if (typeof extension.values.ambient === "string") {
  92273. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92274. }
  92275. else {
  92276. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92277. }
  92278. // Diffuse
  92279. if (typeof extension.values.diffuse === "string") {
  92280. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92281. }
  92282. else {
  92283. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92284. }
  92285. // Emission
  92286. if (typeof extension.values.emission === "string") {
  92287. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92288. }
  92289. else {
  92290. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92291. }
  92292. // Specular
  92293. if (typeof extension.values.specular === "string") {
  92294. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92295. }
  92296. else {
  92297. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92298. }
  92299. return true;
  92300. };
  92301. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92302. // Create buffer from texture url
  92303. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92304. // Create texture from buffer
  92305. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92306. }, onError);
  92307. };
  92308. return GLTFMaterialsCommonExtension;
  92309. }(GLTF1.GLTFLoaderExtension));
  92310. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92311. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92312. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92313. })(BABYLON || (BABYLON = {}));
  92314. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92315. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92316. var BABYLON;
  92317. (function (BABYLON) {
  92318. var GLTF2;
  92319. (function (GLTF2) {
  92320. var ArrayItem = /** @class */ (function () {
  92321. function ArrayItem() {
  92322. }
  92323. ArrayItem.Assign = function (values) {
  92324. if (values) {
  92325. for (var index = 0; index < values.length; index++) {
  92326. values[index]._index = index;
  92327. }
  92328. }
  92329. };
  92330. return ArrayItem;
  92331. }());
  92332. GLTF2.ArrayItem = ArrayItem;
  92333. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92334. })(BABYLON || (BABYLON = {}));
  92335. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92336. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92337. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92338. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92339. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92340. var BABYLON;
  92341. (function (BABYLON) {
  92342. var GLTF2;
  92343. (function (GLTF2) {
  92344. var GLTFLoader = /** @class */ (function () {
  92345. function GLTFLoader() {
  92346. this._completePromises = new Array();
  92347. this._disposed = false;
  92348. this._state = null;
  92349. this._extensions = {};
  92350. this._defaultSampler = {};
  92351. this._requests = new Array();
  92352. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92353. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92354. this.compileMaterials = false;
  92355. this.useClipPlane = false;
  92356. this.compileShadowGenerators = false;
  92357. this.onDisposeObservable = new BABYLON.Observable();
  92358. this.onMeshLoadedObservable = new BABYLON.Observable();
  92359. this.onTextureLoadedObservable = new BABYLON.Observable();
  92360. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92361. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92362. this.onCompleteObservable = new BABYLON.Observable();
  92363. }
  92364. GLTFLoader._Register = function (name, factory) {
  92365. if (GLTFLoader._Factories[name]) {
  92366. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92367. return;
  92368. }
  92369. GLTFLoader._Factories[name] = factory;
  92370. // Keep the order of registration so that extensions registered first are called first.
  92371. GLTFLoader._Names.push(name);
  92372. };
  92373. Object.defineProperty(GLTFLoader.prototype, "state", {
  92374. get: function () {
  92375. return this._state;
  92376. },
  92377. enumerable: true,
  92378. configurable: true
  92379. });
  92380. GLTFLoader.prototype.dispose = function () {
  92381. if (this._disposed) {
  92382. return;
  92383. }
  92384. this._disposed = true;
  92385. this.onDisposeObservable.notifyObservers(this);
  92386. this.onDisposeObservable.clear();
  92387. this._clear();
  92388. };
  92389. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92390. var _this = this;
  92391. return Promise.resolve().then(function () {
  92392. var nodes = null;
  92393. if (meshesNames) {
  92394. var nodeMap_1 = {};
  92395. if (_this._gltf.nodes) {
  92396. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92397. var node = _a[_i];
  92398. if (node.name) {
  92399. nodeMap_1[node.name] = node;
  92400. }
  92401. }
  92402. }
  92403. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92404. nodes = names.map(function (name) {
  92405. var node = nodeMap_1[name];
  92406. if (!node) {
  92407. throw new Error("Failed to find node " + name);
  92408. }
  92409. return node;
  92410. });
  92411. }
  92412. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92413. return {
  92414. meshes: _this._getMeshes(),
  92415. particleSystems: [],
  92416. skeletons: _this._getSkeletons(),
  92417. };
  92418. });
  92419. });
  92420. };
  92421. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92422. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92423. };
  92424. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92425. var _this = this;
  92426. return Promise.resolve().then(function () {
  92427. _this._loadExtensions();
  92428. _this._babylonScene = scene;
  92429. _this._rootUrl = rootUrl;
  92430. _this._progressCallback = onProgress;
  92431. _this._state = BABYLON.GLTFLoaderState.Loading;
  92432. _this._loadData(data);
  92433. _this._checkExtensions();
  92434. var promises = new Array();
  92435. if (nodes) {
  92436. promises.push(_this._loadNodesAsync(nodes));
  92437. }
  92438. else {
  92439. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92440. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92441. }
  92442. if (_this.compileMaterials) {
  92443. promises.push(_this._compileMaterialsAsync());
  92444. }
  92445. if (_this.compileShadowGenerators) {
  92446. promises.push(_this._compileShadowGeneratorsAsync());
  92447. }
  92448. return Promise.all(promises).then(function () {
  92449. _this._state = BABYLON.GLTFLoaderState.Ready;
  92450. _this._startAnimations();
  92451. BABYLON.Tools.SetImmediate(function () {
  92452. if (!_this._disposed) {
  92453. Promise.all(_this._completePromises).then(function () {
  92454. _this._state = BABYLON.GLTFLoaderState.Complete;
  92455. _this.onCompleteObservable.notifyObservers(_this);
  92456. _this.onCompleteObservable.clear();
  92457. _this._clear();
  92458. }).catch(function (error) {
  92459. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92460. _this._clear();
  92461. });
  92462. }
  92463. });
  92464. });
  92465. }).catch(function (error) {
  92466. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92467. _this._clear();
  92468. throw error;
  92469. });
  92470. };
  92471. GLTFLoader.prototype._loadExtensions = function () {
  92472. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92473. var name_1 = _a[_i];
  92474. var extension = GLTFLoader._Factories[name_1](this);
  92475. this._extensions[name_1] = extension;
  92476. this.onExtensionLoadedObservable.notifyObservers(extension);
  92477. }
  92478. this.onExtensionLoadedObservable.clear();
  92479. };
  92480. GLTFLoader.prototype._loadData = function (data) {
  92481. this._gltf = data.json;
  92482. this._setupData();
  92483. if (data.bin) {
  92484. var buffers = this._gltf.buffers;
  92485. if (buffers && buffers[0] && !buffers[0].uri) {
  92486. var binaryBuffer = buffers[0];
  92487. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92488. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92489. }
  92490. binaryBuffer._data = Promise.resolve(data.bin);
  92491. }
  92492. else {
  92493. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92494. }
  92495. }
  92496. };
  92497. GLTFLoader.prototype._setupData = function () {
  92498. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92499. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92500. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92501. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92502. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92503. GLTF2.ArrayItem.Assign(this._gltf.images);
  92504. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92505. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92506. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92507. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92508. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92509. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92510. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92511. if (this._gltf.nodes) {
  92512. var nodeParents = {};
  92513. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92514. var node = _a[_i];
  92515. if (node.children) {
  92516. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92517. var index = _c[_b];
  92518. nodeParents[index] = node._index;
  92519. }
  92520. }
  92521. }
  92522. var rootNode = this._createRootNode();
  92523. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92524. var node = _e[_d];
  92525. var parentIndex = nodeParents[node._index];
  92526. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92527. }
  92528. }
  92529. };
  92530. GLTFLoader.prototype._checkExtensions = function () {
  92531. if (this._gltf.extensionsRequired) {
  92532. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92533. var name_2 = _a[_i];
  92534. var extension = this._extensions[name_2];
  92535. if (!extension || !extension.enabled) {
  92536. throw new Error("Require extension " + name_2 + " is not available");
  92537. }
  92538. }
  92539. }
  92540. };
  92541. GLTFLoader.prototype._createRootNode = function () {
  92542. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92543. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92544. switch (this.coordinateSystemMode) {
  92545. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92546. if (!this._babylonScene.useRightHandedSystem) {
  92547. rootNode.rotation = [0, 1, 0, 0];
  92548. rootNode.scale = [1, 1, -1];
  92549. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92550. }
  92551. break;
  92552. }
  92553. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92554. this._babylonScene.useRightHandedSystem = true;
  92555. break;
  92556. }
  92557. default: {
  92558. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92559. }
  92560. }
  92561. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92562. return rootNode;
  92563. };
  92564. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92565. var promises = new Array();
  92566. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92567. var node = nodes_1[_i];
  92568. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92569. }
  92570. promises.push(this._loadAnimationsAsync());
  92571. return Promise.all(promises).then(function () { });
  92572. };
  92573. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92574. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92575. if (promise) {
  92576. return promise;
  92577. }
  92578. var promises = new Array();
  92579. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92580. var index = _a[_i];
  92581. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92582. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92583. }
  92584. promises.push(this._loadAnimationsAsync());
  92585. return Promise.all(promises).then(function () { });
  92586. };
  92587. GLTFLoader.prototype._getMeshes = function () {
  92588. var meshes = new Array();
  92589. // Root mesh is always first.
  92590. meshes.push(this._rootBabylonMesh);
  92591. var nodes = this._gltf.nodes;
  92592. if (nodes) {
  92593. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92594. var node = nodes_2[_i];
  92595. if (node._babylonMesh) {
  92596. meshes.push(node._babylonMesh);
  92597. }
  92598. if (node._primitiveBabylonMeshes) {
  92599. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92600. var babylonMesh = _b[_a];
  92601. meshes.push(babylonMesh);
  92602. }
  92603. }
  92604. }
  92605. }
  92606. return meshes;
  92607. };
  92608. GLTFLoader.prototype._getSkeletons = function () {
  92609. var skeletons = new Array();
  92610. var skins = this._gltf.skins;
  92611. if (skins) {
  92612. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92613. var skin = skins_1[_i];
  92614. if (skin._babylonSkeleton) {
  92615. skeletons.push(skin._babylonSkeleton);
  92616. }
  92617. }
  92618. }
  92619. return skeletons;
  92620. };
  92621. GLTFLoader.prototype._startAnimations = function () {
  92622. var animations = this._gltf.animations;
  92623. if (!animations) {
  92624. return;
  92625. }
  92626. switch (this.animationStartMode) {
  92627. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92628. // do nothing
  92629. break;
  92630. }
  92631. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92632. var animation = animations[0];
  92633. animation._babylonAnimationGroup.start(true);
  92634. break;
  92635. }
  92636. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92637. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92638. var animation = animations_1[_i];
  92639. animation._babylonAnimationGroup.start(true);
  92640. }
  92641. break;
  92642. }
  92643. default: {
  92644. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92645. return;
  92646. }
  92647. }
  92648. };
  92649. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92650. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92651. if (promise) {
  92652. return promise;
  92653. }
  92654. if (node._babylonMesh) {
  92655. throw new Error(context + ": Invalid recursive node hierarchy");
  92656. }
  92657. var promises = new Array();
  92658. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92659. node._babylonMesh = babylonMesh;
  92660. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92661. node._babylonAnimationTargets.push(babylonMesh);
  92662. GLTFLoader._LoadTransform(node, babylonMesh);
  92663. if (node.mesh != undefined) {
  92664. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92665. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92666. }
  92667. if (node.children) {
  92668. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92669. var index = _a[_i];
  92670. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92671. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92672. }
  92673. }
  92674. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92675. return Promise.all(promises).then(function () { });
  92676. };
  92677. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92678. // TODO: instancing
  92679. var promises = new Array();
  92680. var primitives = mesh.primitives;
  92681. if (!primitives || primitives.length === 0) {
  92682. throw new Error(context + ": Primitives are missing");
  92683. }
  92684. GLTF2.ArrayItem.Assign(primitives);
  92685. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92686. var primitive = primitives_1[_i];
  92687. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92688. }
  92689. if (node.skin != undefined) {
  92690. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92691. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92692. }
  92693. return Promise.all(promises).then(function () {
  92694. if (node._primitiveBabylonMeshes) {
  92695. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92696. var primitiveBabylonMesh = _a[_i];
  92697. primitiveBabylonMesh._refreshBoundingInfo(true);
  92698. }
  92699. }
  92700. });
  92701. };
  92702. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92703. var _this = this;
  92704. var promises = new Array();
  92705. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92706. babylonMesh.setEnabled(false);
  92707. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92708. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92709. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92710. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92711. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92712. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92713. }));
  92714. if (primitive.material == undefined) {
  92715. babylonMesh.material = this._getDefaultMaterial();
  92716. }
  92717. else {
  92718. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92719. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  92720. }
  92721. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92722. return Promise.all(promises).then(function () {
  92723. babylonMesh.setEnabled(true);
  92724. });
  92725. };
  92726. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92727. var _this = this;
  92728. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92729. if (promise) {
  92730. return promise;
  92731. }
  92732. var attributes = primitive.attributes;
  92733. if (!attributes) {
  92734. throw new Error(context + ": Attributes are missing");
  92735. }
  92736. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92737. // TODO: handle other primitive modes
  92738. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92739. }
  92740. var promises = new Array();
  92741. var babylonVertexData = new BABYLON.VertexData();
  92742. if (primitive.indices == undefined) {
  92743. var positionAccessorIndex = attributes["POSITION"];
  92744. if (positionAccessorIndex != undefined) {
  92745. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92746. babylonVertexData.indices = new Uint32Array(accessor.count);
  92747. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92748. babylonVertexData.indices[i] = i;
  92749. }
  92750. }
  92751. }
  92752. else {
  92753. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92754. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92755. babylonVertexData.indices = data;
  92756. }));
  92757. }
  92758. var loadAttribute = function (attribute, kind) {
  92759. if (attributes[attribute] == undefined) {
  92760. return;
  92761. }
  92762. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92763. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92764. babylonMesh._delayInfo.push(kind);
  92765. }
  92766. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92767. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92768. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92769. if (attribute === "COLOR_0") {
  92770. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92771. babylonMesh.hasVertexAlpha = true;
  92772. if (accessor.type === "VEC3") {
  92773. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92774. }
  92775. }
  92776. babylonVertexData.set(attributeData, kind);
  92777. }));
  92778. };
  92779. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92780. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92781. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92782. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92783. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92784. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92785. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92786. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92787. return Promise.all(promises).then(function () {
  92788. return babylonVertexData;
  92789. });
  92790. };
  92791. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92792. if (!primitive.targets) {
  92793. return;
  92794. }
  92795. if (node._numMorphTargets == undefined) {
  92796. node._numMorphTargets = primitive.targets.length;
  92797. }
  92798. else if (primitive.targets.length !== node._numMorphTargets) {
  92799. throw new Error(context + ": Primitives do not have the same number of targets");
  92800. }
  92801. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92802. for (var index = 0; index < primitive.targets.length; index++) {
  92803. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92804. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92805. // TODO: tell the target whether it has positions, normals, tangents
  92806. }
  92807. };
  92808. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92809. if (!primitive.targets) {
  92810. return Promise.resolve();
  92811. }
  92812. var promises = new Array();
  92813. var morphTargetManager = babylonMesh.morphTargetManager;
  92814. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92815. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92816. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92817. }
  92818. return Promise.all(promises).then(function () { });
  92819. };
  92820. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92821. var _this = this;
  92822. var promises = new Array();
  92823. var loadAttribute = function (attribute, setData) {
  92824. if (attributes[attribute] == undefined) {
  92825. return;
  92826. }
  92827. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92828. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92829. setData(data);
  92830. }));
  92831. };
  92832. loadAttribute("POSITION", function (data) {
  92833. if (babylonVertexData.positions) {
  92834. for (var i = 0; i < data.length; i++) {
  92835. data[i] += babylonVertexData.positions[i];
  92836. }
  92837. babylonMorphTarget.setPositions(data);
  92838. }
  92839. });
  92840. loadAttribute("NORMAL", function (data) {
  92841. if (babylonVertexData.normals) {
  92842. for (var i = 0; i < data.length; i++) {
  92843. data[i] += babylonVertexData.normals[i];
  92844. }
  92845. babylonMorphTarget.setNormals(data);
  92846. }
  92847. });
  92848. loadAttribute("TANGENT", function (data) {
  92849. if (babylonVertexData.tangents) {
  92850. // Tangent data for morph targets is stored as xyz delta.
  92851. // The vertexData.tangent is stored as xyzw.
  92852. // So we need to skip every fourth vertexData.tangent.
  92853. for (var i = 0, j = 0; i < data.length; i++) {
  92854. data[i] += babylonVertexData.tangents[j++];
  92855. if ((i + 1) % 3 == 0) {
  92856. j++;
  92857. }
  92858. }
  92859. babylonMorphTarget.setTangents(data);
  92860. }
  92861. });
  92862. return Promise.all(promises).then(function () { });
  92863. };
  92864. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92865. if (accessor.componentType == 5126 /* FLOAT */) {
  92866. return data;
  92867. }
  92868. var factor = 1;
  92869. if (accessor.normalized) {
  92870. switch (accessor.componentType) {
  92871. case 5121 /* UNSIGNED_BYTE */: {
  92872. factor = 1 / 255;
  92873. break;
  92874. }
  92875. case 5123 /* UNSIGNED_SHORT */: {
  92876. factor = 1 / 65535;
  92877. break;
  92878. }
  92879. default: {
  92880. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92881. }
  92882. }
  92883. }
  92884. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92885. for (var i = 0; i < result.length; i++) {
  92886. result[i] = data[i] * factor;
  92887. }
  92888. return result;
  92889. };
  92890. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92891. var result = new Float32Array(data.length / 3 * 4);
  92892. var offset = 0;
  92893. for (var i = 0; i < result.length; i++) {
  92894. if ((i + 1) % 4 === 0) {
  92895. result[i] = 1;
  92896. }
  92897. else {
  92898. result[i] = data[offset++];
  92899. }
  92900. }
  92901. return result;
  92902. };
  92903. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92904. var position = BABYLON.Vector3.Zero();
  92905. var rotation = BABYLON.Quaternion.Identity();
  92906. var scaling = BABYLON.Vector3.One();
  92907. if (node.matrix) {
  92908. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92909. matrix.decompose(scaling, rotation, position);
  92910. }
  92911. else {
  92912. if (node.translation)
  92913. position = BABYLON.Vector3.FromArray(node.translation);
  92914. if (node.rotation)
  92915. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92916. if (node.scale)
  92917. scaling = BABYLON.Vector3.FromArray(node.scale);
  92918. }
  92919. babylonNode.position = position;
  92920. babylonNode.rotationQuaternion = rotation;
  92921. babylonNode.scaling = scaling;
  92922. };
  92923. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92924. var _this = this;
  92925. var assignSkeleton = function () {
  92926. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92927. var babylonMesh = _a[_i];
  92928. babylonMesh.skeleton = skin._babylonSkeleton;
  92929. }
  92930. node._babylonMesh.parent = _this._rootBabylonMesh;
  92931. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92932. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92933. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92934. };
  92935. if (skin._loaded) {
  92936. return skin._loaded.then(function () {
  92937. assignSkeleton();
  92938. });
  92939. }
  92940. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  92941. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  92942. var skeletonId = "skeleton" + skin._index;
  92943. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  92944. skin._babylonSkeleton = babylonSkeleton;
  92945. _this._loadBones(context, skin, inverseBindMatricesData);
  92946. assignSkeleton();
  92947. }));
  92948. };
  92949. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  92950. if (skin.inverseBindMatrices == undefined) {
  92951. return Promise.resolve(null);
  92952. }
  92953. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  92954. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92955. return data;
  92956. });
  92957. };
  92958. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  92959. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  92960. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92961. node._babylonAnimationTargets.push(babylonBone);
  92962. return babylonBone;
  92963. };
  92964. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  92965. var babylonBones = {};
  92966. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  92967. var index = _a[_i];
  92968. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  92969. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  92970. }
  92971. };
  92972. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  92973. var babylonBone = babylonBones[node._index];
  92974. if (babylonBone) {
  92975. return babylonBone;
  92976. }
  92977. var boneIndex = skin.joints.indexOf(node._index);
  92978. var baseMatrix = BABYLON.Matrix.Identity();
  92979. if (inverseBindMatricesData && boneIndex !== -1) {
  92980. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  92981. baseMatrix.invertToRef(baseMatrix);
  92982. }
  92983. var babylonParentBone = null;
  92984. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  92985. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  92986. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  92987. }
  92988. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  92989. babylonBones[node._index] = babylonBone;
  92990. return babylonBone;
  92991. };
  92992. GLTFLoader.prototype._getNodeMatrix = function (node) {
  92993. return node.matrix ?
  92994. BABYLON.Matrix.FromArray(node.matrix) :
  92995. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  92996. };
  92997. GLTFLoader.prototype._loadAnimationsAsync = function () {
  92998. var animations = this._gltf.animations;
  92999. if (!animations) {
  93000. return Promise.resolve();
  93001. }
  93002. var promises = new Array();
  93003. for (var index = 0; index < animations.length; index++) {
  93004. var animation = animations[index];
  93005. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93006. }
  93007. return Promise.all(promises).then(function () { });
  93008. };
  93009. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93010. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93011. animation._babylonAnimationGroup = babylonAnimationGroup;
  93012. var promises = new Array();
  93013. GLTF2.ArrayItem.Assign(animation.channels);
  93014. GLTF2.ArrayItem.Assign(animation.samplers);
  93015. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93016. var channel = _a[_i];
  93017. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93018. }
  93019. return Promise.all(promises).then(function () {
  93020. babylonAnimationGroup.normalize();
  93021. });
  93022. };
  93023. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93024. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93025. if (!targetNode._babylonMesh) {
  93026. return Promise.resolve();
  93027. }
  93028. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93029. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93030. var targetPath;
  93031. var animationType;
  93032. switch (channel.target.path) {
  93033. case "translation" /* TRANSLATION */: {
  93034. targetPath = "position";
  93035. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93036. break;
  93037. }
  93038. case "rotation" /* ROTATION */: {
  93039. targetPath = "rotationQuaternion";
  93040. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93041. break;
  93042. }
  93043. case "scale" /* SCALE */: {
  93044. targetPath = "scaling";
  93045. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93046. break;
  93047. }
  93048. case "weights" /* WEIGHTS */: {
  93049. targetPath = "influence";
  93050. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93051. break;
  93052. }
  93053. default: {
  93054. throw new Error(context + ": Invalid target path " + channel.target.path);
  93055. }
  93056. }
  93057. var outputBufferOffset = 0;
  93058. var getNextOutputValue;
  93059. switch (targetPath) {
  93060. case "position": {
  93061. getNextOutputValue = function () {
  93062. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93063. outputBufferOffset += 3;
  93064. return value;
  93065. };
  93066. break;
  93067. }
  93068. case "rotationQuaternion": {
  93069. getNextOutputValue = function () {
  93070. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93071. outputBufferOffset += 4;
  93072. return value;
  93073. };
  93074. break;
  93075. }
  93076. case "scaling": {
  93077. getNextOutputValue = function () {
  93078. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93079. outputBufferOffset += 3;
  93080. return value;
  93081. };
  93082. break;
  93083. }
  93084. case "influence": {
  93085. getNextOutputValue = function () {
  93086. var value = new Array(targetNode._numMorphTargets);
  93087. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93088. value[i] = data.output[outputBufferOffset++];
  93089. }
  93090. return value;
  93091. };
  93092. break;
  93093. }
  93094. }
  93095. var getNextKey;
  93096. switch (data.interpolation) {
  93097. case "STEP" /* STEP */: {
  93098. getNextKey = function (frameIndex) { return ({
  93099. frame: data.input[frameIndex],
  93100. value: getNextOutputValue(),
  93101. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93102. }); };
  93103. break;
  93104. }
  93105. case "LINEAR" /* LINEAR */: {
  93106. getNextKey = function (frameIndex) { return ({
  93107. frame: data.input[frameIndex],
  93108. value: getNextOutputValue()
  93109. }); };
  93110. break;
  93111. }
  93112. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93113. getNextKey = function (frameIndex) { return ({
  93114. frame: data.input[frameIndex],
  93115. inTangent: getNextOutputValue(),
  93116. value: getNextOutputValue(),
  93117. outTangent: getNextOutputValue()
  93118. }); };
  93119. break;
  93120. }
  93121. }
  93122. var keys;
  93123. if (data.input.length === 1) {
  93124. var key = getNextKey(0);
  93125. keys = [
  93126. { frame: key.frame, value: key.value },
  93127. { frame: key.frame + 1, value: key.value }
  93128. ];
  93129. }
  93130. else {
  93131. keys = new Array(data.input.length);
  93132. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93133. keys[frameIndex] = getNextKey(frameIndex);
  93134. }
  93135. }
  93136. if (targetPath === "influence") {
  93137. var _loop_1 = function (targetIndex) {
  93138. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93139. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93140. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93141. frame: key.frame,
  93142. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93143. value: key.value[targetIndex],
  93144. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93145. }); }));
  93146. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93147. var babylonMesh = _a[_i];
  93148. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93149. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93150. }
  93151. };
  93152. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93153. _loop_1(targetIndex);
  93154. }
  93155. }
  93156. else {
  93157. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93158. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93159. babylonAnimation.setKeys(keys);
  93160. if (targetNode._babylonAnimationTargets) {
  93161. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93162. var target = _a[_i];
  93163. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93164. }
  93165. }
  93166. }
  93167. });
  93168. };
  93169. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93170. if (sampler._data) {
  93171. return sampler._data;
  93172. }
  93173. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93174. switch (interpolation) {
  93175. case "STEP" /* STEP */:
  93176. case "LINEAR" /* LINEAR */:
  93177. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93178. break;
  93179. }
  93180. default: {
  93181. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  93182. }
  93183. }
  93184. var inputData;
  93185. var outputData;
  93186. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93187. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93188. sampler._data = Promise.all([
  93189. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93190. inputData = data;
  93191. }),
  93192. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93193. outputData = data;
  93194. })
  93195. ]).then(function () {
  93196. return {
  93197. input: inputData,
  93198. interpolation: interpolation,
  93199. output: outputData,
  93200. };
  93201. });
  93202. return sampler._data;
  93203. };
  93204. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93205. if (buffer._data) {
  93206. return buffer._data;
  93207. }
  93208. if (!buffer.uri) {
  93209. throw new Error(context + ": Uri is missing");
  93210. }
  93211. buffer._data = this._loadUriAsync(context, buffer.uri);
  93212. return buffer._data;
  93213. };
  93214. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93215. if (bufferView._data) {
  93216. return bufferView._data;
  93217. }
  93218. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93219. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93220. try {
  93221. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93222. }
  93223. catch (e) {
  93224. throw new Error(context + ": " + e.message);
  93225. }
  93226. });
  93227. return bufferView._data;
  93228. };
  93229. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93230. var _this = this;
  93231. if (accessor.sparse) {
  93232. throw new Error(context + ": Sparse accessors are not currently supported");
  93233. }
  93234. if (accessor._data) {
  93235. return accessor._data;
  93236. }
  93237. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93238. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93239. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93240. var byteOffset = accessor.byteOffset || 0;
  93241. var byteStride = bufferView.byteStride;
  93242. if (byteStride === 0) {
  93243. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93244. }
  93245. try {
  93246. switch (accessor.componentType) {
  93247. case 5120 /* BYTE */: {
  93248. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93249. }
  93250. case 5121 /* UNSIGNED_BYTE */: {
  93251. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93252. }
  93253. case 5122 /* SHORT */: {
  93254. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93255. }
  93256. case 5123 /* UNSIGNED_SHORT */: {
  93257. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93258. }
  93259. case 5125 /* UNSIGNED_INT */: {
  93260. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93261. }
  93262. case 5126 /* FLOAT */: {
  93263. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93264. }
  93265. default: {
  93266. throw new Error(context + ": Invalid component type " + accessor.componentType);
  93267. }
  93268. }
  93269. }
  93270. catch (e) {
  93271. throw new Error(context + ": " + e);
  93272. }
  93273. });
  93274. return accessor._data;
  93275. };
  93276. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93277. byteOffset += data.byteOffset;
  93278. var targetLength = count * numComponents;
  93279. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93280. return new typedArray(data.buffer, byteOffset, targetLength);
  93281. }
  93282. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93283. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93284. var targetBuffer = new typedArray(targetLength);
  93285. var sourceIndex = 0;
  93286. var targetIndex = 0;
  93287. while (targetIndex < targetLength) {
  93288. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93289. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93290. targetIndex++;
  93291. }
  93292. sourceIndex += elementStride;
  93293. }
  93294. return targetBuffer;
  93295. };
  93296. GLTFLoader.prototype._getDefaultMaterial = function () {
  93297. var id = "__gltf_default";
  93298. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93299. if (!babylonMaterial) {
  93300. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93301. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93302. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93303. babylonMaterial.metallic = 1;
  93304. babylonMaterial.roughness = 1;
  93305. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93306. }
  93307. return babylonMaterial;
  93308. };
  93309. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93310. var promises = new Array();
  93311. var babylonMaterial = material._babylonMaterial;
  93312. // Ensure metallic workflow
  93313. babylonMaterial.metallic = 1;
  93314. babylonMaterial.roughness = 1;
  93315. var properties = material.pbrMetallicRoughness;
  93316. if (properties) {
  93317. if (properties.baseColorFactor) {
  93318. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93319. babylonMaterial.alpha = properties.baseColorFactor[3];
  93320. }
  93321. else {
  93322. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93323. }
  93324. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93325. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93326. if (properties.baseColorTexture) {
  93327. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93328. babylonMaterial.albedoTexture = texture;
  93329. }));
  93330. }
  93331. if (properties.metallicRoughnessTexture) {
  93332. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93333. babylonMaterial.metallicTexture = texture;
  93334. }));
  93335. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93336. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93337. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93338. }
  93339. }
  93340. this._loadMaterialAlphaProperties(context, material);
  93341. return Promise.all(promises).then(function () { });
  93342. };
  93343. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93344. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  93345. if (promise) {
  93346. return promise;
  93347. }
  93348. material._babylonMeshes = material._babylonMeshes || [];
  93349. material._babylonMeshes.push(babylonMesh);
  93350. if (material._loaded) {
  93351. babylonMesh.material = material._babylonMaterial;
  93352. return material._loaded;
  93353. }
  93354. var promises = new Array();
  93355. var babylonMaterial = this._createMaterial(material);
  93356. material._babylonMaterial = babylonMaterial;
  93357. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93358. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93359. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93360. babylonMesh.material = babylonMaterial;
  93361. return (material._loaded = Promise.all(promises).then(function () { }));
  93362. };
  93363. GLTFLoader.prototype._createMaterial = function (material) {
  93364. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93365. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93366. return babylonMaterial;
  93367. };
  93368. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93369. var promises = new Array();
  93370. var babylonMaterial = material._babylonMaterial;
  93371. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93372. if (material.doubleSided) {
  93373. babylonMaterial.backFaceCulling = false;
  93374. babylonMaterial.twoSidedLighting = true;
  93375. }
  93376. if (material.normalTexture) {
  93377. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93378. babylonMaterial.bumpTexture = texture;
  93379. }));
  93380. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93381. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93382. if (material.normalTexture.scale != undefined) {
  93383. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93384. }
  93385. }
  93386. if (material.occlusionTexture) {
  93387. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93388. babylonMaterial.ambientTexture = texture;
  93389. }));
  93390. babylonMaterial.useAmbientInGrayScale = true;
  93391. if (material.occlusionTexture.strength != undefined) {
  93392. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93393. }
  93394. }
  93395. if (material.emissiveTexture) {
  93396. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93397. babylonMaterial.emissiveTexture = texture;
  93398. }));
  93399. }
  93400. return Promise.all(promises).then(function () { });
  93401. };
  93402. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93403. var babylonMaterial = material._babylonMaterial;
  93404. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93405. switch (alphaMode) {
  93406. case "OPAQUE" /* OPAQUE */: {
  93407. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93408. break;
  93409. }
  93410. case "MASK" /* MASK */: {
  93411. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93412. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93413. if (babylonMaterial.alpha) {
  93414. if (babylonMaterial.alpha === 0) {
  93415. babylonMaterial.alphaCutOff = 1;
  93416. }
  93417. else {
  93418. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93419. }
  93420. babylonMaterial.alpha = 1;
  93421. }
  93422. if (babylonMaterial.albedoTexture) {
  93423. babylonMaterial.albedoTexture.hasAlpha = true;
  93424. }
  93425. break;
  93426. }
  93427. case "BLEND" /* BLEND */: {
  93428. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93429. if (babylonMaterial.albedoTexture) {
  93430. babylonMaterial.albedoTexture.hasAlpha = true;
  93431. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93432. }
  93433. break;
  93434. }
  93435. default: {
  93436. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  93437. }
  93438. }
  93439. };
  93440. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93441. var _this = this;
  93442. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93443. context = "#/textures/" + textureInfo.index;
  93444. var promises = new Array();
  93445. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93446. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93447. var deferred = new BABYLON.Deferred();
  93448. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93449. if (!_this._disposed) {
  93450. deferred.resolve();
  93451. }
  93452. }, function (message, exception) {
  93453. if (!_this._disposed) {
  93454. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  93455. }
  93456. });
  93457. promises.push(deferred.promise);
  93458. babylonTexture.name = texture.name || "texture" + texture._index;
  93459. babylonTexture.wrapU = samplerData.wrapU;
  93460. babylonTexture.wrapV = samplerData.wrapV;
  93461. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93462. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93463. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93464. babylonTexture.updateURL(objectURL);
  93465. }));
  93466. assign(babylonTexture);
  93467. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93468. return Promise.all(promises).then(function () { });
  93469. };
  93470. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93471. if (!sampler._data) {
  93472. sampler._data = {
  93473. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93474. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93475. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93476. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93477. };
  93478. }
  93479. ;
  93480. return sampler._data;
  93481. };
  93482. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93483. if (image._objectURL) {
  93484. return image._objectURL;
  93485. }
  93486. var promise;
  93487. if (image.uri) {
  93488. promise = this._loadUriAsync(context, image.uri);
  93489. }
  93490. else {
  93491. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93492. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93493. }
  93494. image._objectURL = promise.then(function (data) {
  93495. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93496. });
  93497. return image._objectURL;
  93498. };
  93499. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93500. var _this = this;
  93501. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93502. if (promise) {
  93503. return promise;
  93504. }
  93505. if (!GLTFLoader._ValidateUri(uri)) {
  93506. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93507. }
  93508. if (BABYLON.Tools.IsBase64(uri)) {
  93509. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93510. }
  93511. return new Promise(function (resolve, reject) {
  93512. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93513. if (!_this._disposed) {
  93514. resolve(new Uint8Array(data));
  93515. }
  93516. }, function (event) {
  93517. if (!_this._disposed) {
  93518. try {
  93519. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93520. request._lengthComputable = event.lengthComputable;
  93521. request._loaded = event.loaded;
  93522. request._total = event.total;
  93523. _this._onProgress();
  93524. }
  93525. }
  93526. catch (e) {
  93527. reject(e);
  93528. }
  93529. }
  93530. }, _this._babylonScene.database, true, function (request, exception) {
  93531. if (!_this._disposed) {
  93532. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93533. }
  93534. });
  93535. _this._requests.push(request);
  93536. });
  93537. };
  93538. GLTFLoader.prototype._onProgress = function () {
  93539. if (!this._progressCallback) {
  93540. return;
  93541. }
  93542. var lengthComputable = true;
  93543. var loaded = 0;
  93544. var total = 0;
  93545. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93546. var request = _a[_i];
  93547. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93548. return;
  93549. }
  93550. lengthComputable = lengthComputable && request._lengthComputable;
  93551. loaded += request._loaded;
  93552. total += request._total;
  93553. }
  93554. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93555. };
  93556. GLTFLoader._GetProperty = function (context, array, index) {
  93557. if (!array || index == undefined || !array[index]) {
  93558. throw new Error(context + ": Failed to find index " + index);
  93559. }
  93560. return array[index];
  93561. };
  93562. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93563. // Set defaults if undefined
  93564. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93565. switch (mode) {
  93566. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93567. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93568. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93569. default:
  93570. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93571. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93572. }
  93573. };
  93574. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93575. // Set defaults if undefined
  93576. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93577. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93578. if (magFilter === 9729 /* LINEAR */) {
  93579. switch (minFilter) {
  93580. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93581. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93582. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93583. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93584. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93585. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93586. default:
  93587. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93588. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93589. }
  93590. }
  93591. else {
  93592. if (magFilter !== 9728 /* NEAREST */) {
  93593. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93594. }
  93595. switch (minFilter) {
  93596. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93597. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93598. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93599. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93600. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93601. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93602. default:
  93603. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93604. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93605. }
  93606. }
  93607. };
  93608. GLTFLoader._GetNumComponents = function (context, type) {
  93609. switch (type) {
  93610. case "SCALAR": return 1;
  93611. case "VEC2": return 2;
  93612. case "VEC3": return 3;
  93613. case "VEC4": return 4;
  93614. case "MAT2": return 4;
  93615. case "MAT3": return 9;
  93616. case "MAT4": return 16;
  93617. }
  93618. throw new Error(context + ": Invalid type " + type);
  93619. };
  93620. GLTFLoader._ValidateUri = function (uri) {
  93621. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93622. };
  93623. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93624. var promises = new Array();
  93625. if (this._gltf.materials) {
  93626. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93627. var material = _a[_i];
  93628. var babylonMaterial = material._babylonMaterial;
  93629. var babylonMeshes = material._babylonMeshes;
  93630. if (babylonMaterial && babylonMeshes) {
  93631. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93632. var babylonMesh = babylonMeshes_1[_b];
  93633. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93634. if (this.useClipPlane) {
  93635. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93636. }
  93637. }
  93638. }
  93639. }
  93640. }
  93641. return Promise.all(promises).then(function () { });
  93642. };
  93643. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93644. var promises = new Array();
  93645. var lights = this._babylonScene.lights;
  93646. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93647. var light = lights_1[_i];
  93648. var generator = light.getShadowGenerator();
  93649. if (generator) {
  93650. promises.push(generator.forceCompilationAsync());
  93651. }
  93652. }
  93653. return Promise.all(promises).then(function () { });
  93654. };
  93655. GLTFLoader.prototype._clear = function () {
  93656. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93657. var request = _a[_i];
  93658. request.abort();
  93659. }
  93660. this._requests.length = 0;
  93661. if (this._gltf && this._gltf.images) {
  93662. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93663. var image = _c[_b];
  93664. if (image._objectURL) {
  93665. image._objectURL.then(function (value) {
  93666. URL.revokeObjectURL(value);
  93667. });
  93668. image._objectURL = undefined;
  93669. }
  93670. }
  93671. }
  93672. delete this._gltf;
  93673. delete this._babylonScene;
  93674. this._completePromises.length = 0;
  93675. for (var name_3 in this._extensions) {
  93676. this._extensions[name_3].dispose();
  93677. }
  93678. this._extensions = {};
  93679. delete this._rootBabylonMesh;
  93680. delete this._progressCallback;
  93681. this.onMeshLoadedObservable.clear();
  93682. this.onTextureLoadedObservable.clear();
  93683. this.onMaterialLoadedObservable.clear();
  93684. };
  93685. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93686. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93687. var name_4 = _a[_i];
  93688. var extension = this._extensions[name_4];
  93689. if (extension.enabled) {
  93690. var promise = actionAsync(extension);
  93691. if (promise) {
  93692. return promise;
  93693. }
  93694. }
  93695. }
  93696. return null;
  93697. };
  93698. GLTFLoader._Names = new Array();
  93699. GLTFLoader._Factories = {};
  93700. return GLTFLoader;
  93701. }());
  93702. GLTF2.GLTFLoader = GLTFLoader;
  93703. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93704. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93705. })(BABYLON || (BABYLON = {}));
  93706. //# sourceMappingURL=babylon.glTFLoader.js.map
  93707. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93708. var BABYLON;
  93709. (function (BABYLON) {
  93710. var GLTF2;
  93711. (function (GLTF2) {
  93712. var GLTFLoaderExtension = /** @class */ (function () {
  93713. function GLTFLoaderExtension(loader) {
  93714. this.enabled = true;
  93715. this._loader = loader;
  93716. }
  93717. GLTFLoaderExtension.prototype.dispose = function () {
  93718. delete this._loader;
  93719. };
  93720. // #region Overridable Methods
  93721. /** Override this method to modify the default behavior for loading scenes. */
  93722. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93723. /** Override this method to modify the default behavior for loading nodes. */
  93724. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93725. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93726. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93727. /** Override this method to modify the default behavior for loading materials. */
  93728. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  93729. /** Override this method to modify the default behavior for loading uris. */
  93730. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93731. // #endregion
  93732. /** Helper method called by a loader extension to load an glTF extension. */
  93733. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93734. if (!property.extensions) {
  93735. return null;
  93736. }
  93737. var extensions = property.extensions;
  93738. var extension = extensions[this.name];
  93739. if (!extension) {
  93740. return null;
  93741. }
  93742. // Clear out the extension before executing the action to avoid recursing into the same property.
  93743. delete extensions[this.name];
  93744. try {
  93745. return actionAsync(context + "/extensions/" + this.name, extension);
  93746. }
  93747. finally {
  93748. // Restore the extension after executing the action.
  93749. extensions[this.name] = extension;
  93750. }
  93751. };
  93752. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93753. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93754. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93755. };
  93756. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93757. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93758. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93759. };
  93760. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93761. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93762. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93763. };
  93764. /** Helper method called by the loader to allow extensions to override loading materials. */
  93765. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  93766. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  93767. };
  93768. /** Helper method called by the loader to allow extensions to override loading uris. */
  93769. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93770. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93771. };
  93772. return GLTFLoaderExtension;
  93773. }());
  93774. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93775. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93776. })(BABYLON || (BABYLON = {}));
  93777. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93778. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93779. var BABYLON;
  93780. (function (BABYLON) {
  93781. var GLTF2;
  93782. (function (GLTF2) {
  93783. var Extensions;
  93784. (function (Extensions) {
  93785. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93786. var NAME = "MSFT_lod";
  93787. var MSFT_lod = /** @class */ (function (_super) {
  93788. __extends(MSFT_lod, _super);
  93789. function MSFT_lod() {
  93790. var _this = _super !== null && _super.apply(this, arguments) || this;
  93791. _this.name = NAME;
  93792. /**
  93793. * Maximum number of LODs to load, starting from the lowest LOD.
  93794. */
  93795. _this.maxLODsToLoad = Number.MAX_VALUE;
  93796. _this._loadingNodeLOD = null;
  93797. _this._loadNodeSignals = {};
  93798. _this._loadingMaterialLOD = null;
  93799. _this._loadMaterialSignals = {};
  93800. return _this;
  93801. }
  93802. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93803. var _this = this;
  93804. return this._loadExtensionAsync(context, node, function (context, extension) {
  93805. var firstPromise;
  93806. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93807. var _loop_1 = function (indexLOD) {
  93808. var nodeLOD = nodeLODs[indexLOD];
  93809. if (indexLOD !== 0) {
  93810. _this._loadingNodeLOD = nodeLOD;
  93811. if (!_this._loadNodeSignals[nodeLOD._index]) {
  93812. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93813. }
  93814. }
  93815. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93816. if (indexLOD !== 0) {
  93817. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93818. previousNodeLOD._babylonMesh.setEnabled(false);
  93819. }
  93820. if (indexLOD !== nodeLODs.length - 1) {
  93821. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93822. if (_this._loadNodeSignals[nodeIndex]) {
  93823. _this._loadNodeSignals[nodeIndex].resolve();
  93824. delete _this._loadNodeSignals[nodeIndex];
  93825. }
  93826. }
  93827. });
  93828. if (indexLOD === 0) {
  93829. firstPromise = promise;
  93830. }
  93831. else {
  93832. _this._loader._completePromises.push(promise);
  93833. _this._loadingNodeLOD = null;
  93834. }
  93835. };
  93836. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93837. _loop_1(indexLOD);
  93838. }
  93839. return firstPromise;
  93840. });
  93841. };
  93842. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93843. var _this = this;
  93844. // Don't load material LODs if already loading a node LOD.
  93845. if (this._loadingNodeLOD) {
  93846. return null;
  93847. }
  93848. return this._loadExtensionAsync(context, material, function (context, extension) {
  93849. var firstPromise;
  93850. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93851. var _loop_2 = function (indexLOD) {
  93852. var materialLOD = materialLODs[indexLOD];
  93853. if (indexLOD !== 0) {
  93854. _this._loadingMaterialLOD = materialLOD;
  93855. if (!_this._loadMaterialSignals[materialLOD._index]) {
  93856. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93857. }
  93858. }
  93859. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  93860. if (indexLOD !== materialLODs.length - 1) {
  93861. var materialIndex = materialLODs[indexLOD + 1]._index;
  93862. if (_this._loadMaterialSignals[materialIndex]) {
  93863. _this._loadMaterialSignals[materialIndex].resolve();
  93864. delete _this._loadMaterialSignals[materialIndex];
  93865. }
  93866. }
  93867. });
  93868. if (indexLOD === 0) {
  93869. firstPromise = promise;
  93870. }
  93871. else {
  93872. _this._loader._completePromises.push(promise);
  93873. _this._loadingMaterialLOD = null;
  93874. }
  93875. };
  93876. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93877. _loop_2(indexLOD);
  93878. }
  93879. return firstPromise;
  93880. });
  93881. };
  93882. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93883. var _this = this;
  93884. // Defer the loading of uris if loading a material or node LOD.
  93885. if (this._loadingMaterialLOD) {
  93886. var index = this._loadingMaterialLOD._index;
  93887. return this._loadMaterialSignals[index].promise.then(function () {
  93888. return _this._loader._loadUriAsync(context, uri);
  93889. });
  93890. }
  93891. else if (this._loadingNodeLOD) {
  93892. var index = this._loadingNodeLOD._index;
  93893. return this._loadNodeSignals[index].promise.then(function () {
  93894. return _this._loader._loadUriAsync(context, uri);
  93895. });
  93896. }
  93897. return null;
  93898. };
  93899. /**
  93900. * Gets an array of LOD properties from lowest to highest.
  93901. */
  93902. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93903. if (this.maxLODsToLoad <= 0) {
  93904. throw new Error("maxLODsToLoad must be greater than zero");
  93905. }
  93906. var properties = new Array();
  93907. for (var i = ids.length - 1; i >= 0; i--) {
  93908. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93909. if (properties.length === this.maxLODsToLoad) {
  93910. return properties;
  93911. }
  93912. }
  93913. properties.push(property);
  93914. return properties;
  93915. };
  93916. return MSFT_lod;
  93917. }(GLTF2.GLTFLoaderExtension));
  93918. Extensions.MSFT_lod = MSFT_lod;
  93919. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93920. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93921. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93922. })(BABYLON || (BABYLON = {}));
  93923. //# sourceMappingURL=MSFT_lod.js.map
  93924. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93925. var BABYLON;
  93926. (function (BABYLON) {
  93927. var GLTF2;
  93928. (function (GLTF2) {
  93929. var Extensions;
  93930. (function (Extensions) {
  93931. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93932. var NAME = "KHR_draco_mesh_compression";
  93933. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93934. __extends(KHR_draco_mesh_compression, _super);
  93935. function KHR_draco_mesh_compression(loader) {
  93936. var _this = _super.call(this, loader) || this;
  93937. _this.name = NAME;
  93938. _this._dracoCompression = null;
  93939. // Disable extension if decoder is not available.
  93940. if (!BABYLON.DracoCompression.DecoderUrl) {
  93941. _this.enabled = false;
  93942. }
  93943. return _this;
  93944. }
  93945. KHR_draco_mesh_compression.prototype.dispose = function () {
  93946. if (this._dracoCompression) {
  93947. this._dracoCompression.dispose();
  93948. }
  93949. _super.prototype.dispose.call(this);
  93950. };
  93951. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93952. var _this = this;
  93953. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  93954. if (primitive.mode != undefined) {
  93955. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  93956. primitive.mode !== 4 /* TRIANGLES */) {
  93957. throw new Error(context + ": Unsupported mode " + primitive.mode);
  93958. }
  93959. // TODO: handle triangle strips
  93960. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  93961. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  93962. }
  93963. }
  93964. var attributes = {};
  93965. var loadAttribute = function (name, kind) {
  93966. var uniqueId = extension.attributes[name];
  93967. if (uniqueId == undefined) {
  93968. return;
  93969. }
  93970. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93971. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93972. babylonMesh._delayInfo.push(kind);
  93973. }
  93974. attributes[kind] = uniqueId;
  93975. };
  93976. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93977. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93978. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93979. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93980. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93981. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93982. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93983. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93984. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  93985. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  93986. try {
  93987. if (!_this._dracoCompression) {
  93988. _this._dracoCompression = new BABYLON.DracoCompression();
  93989. }
  93990. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  93991. }
  93992. catch (e) {
  93993. throw new Error(context + ": " + e.message);
  93994. }
  93995. });
  93996. });
  93997. };
  93998. return KHR_draco_mesh_compression;
  93999. }(GLTF2.GLTFLoaderExtension));
  94000. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94001. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94002. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94003. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94004. })(BABYLON || (BABYLON = {}));
  94005. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94006. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94007. var BABYLON;
  94008. (function (BABYLON) {
  94009. var GLTF2;
  94010. (function (GLTF2) {
  94011. var Extensions;
  94012. (function (Extensions) {
  94013. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94014. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94015. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94016. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94017. function KHR_materials_pbrSpecularGlossiness() {
  94018. var _this = _super !== null && _super.apply(this, arguments) || this;
  94019. _this.name = NAME;
  94020. return _this;
  94021. }
  94022. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  94023. var _this = this;
  94024. return this._loadExtensionAsync(context, material, function (context, extension) {
  94025. material._babylonMeshes = material._babylonMeshes || [];
  94026. material._babylonMeshes.push(babylonMesh);
  94027. if (material._loaded) {
  94028. babylonMesh.material = material._babylonMaterial;
  94029. return material._loaded;
  94030. }
  94031. var promises = new Array();
  94032. var babylonMaterial = _this._loader._createMaterial(material);
  94033. material._babylonMaterial = babylonMaterial;
  94034. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94035. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  94036. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94037. babylonMesh.material = babylonMaterial;
  94038. return (material._loaded = Promise.all(promises).then(function () { }));
  94039. });
  94040. };
  94041. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  94042. var promises = new Array();
  94043. var babylonMaterial = material._babylonMaterial;
  94044. if (properties.diffuseFactor) {
  94045. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94046. babylonMaterial.alpha = properties.diffuseFactor[3];
  94047. }
  94048. else {
  94049. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94050. }
  94051. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94052. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94053. if (properties.diffuseTexture) {
  94054. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94055. babylonMaterial.albedoTexture = texture;
  94056. }));
  94057. }
  94058. if (properties.specularGlossinessTexture) {
  94059. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94060. babylonMaterial.reflectivityTexture = texture;
  94061. }));
  94062. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94063. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94064. }
  94065. loader._loadMaterialAlphaProperties(context, material);
  94066. return Promise.all(promises).then(function () { });
  94067. };
  94068. return KHR_materials_pbrSpecularGlossiness;
  94069. }(GLTF2.GLTFLoaderExtension));
  94070. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94071. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94072. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94073. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94074. })(BABYLON || (BABYLON = {}));
  94075. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94076. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94077. var BABYLON;
  94078. (function (BABYLON) {
  94079. var GLTF2;
  94080. (function (GLTF2) {
  94081. var Extensions;
  94082. (function (Extensions) {
  94083. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94084. var NAME = "KHR_lights";
  94085. var LightType;
  94086. (function (LightType) {
  94087. LightType["AMBIENT"] = "ambient";
  94088. LightType["DIRECTIONAL"] = "directional";
  94089. LightType["POINT"] = "point";
  94090. LightType["SPOT"] = "spot";
  94091. })(LightType || (LightType = {}));
  94092. var KHR_lights = /** @class */ (function (_super) {
  94093. __extends(KHR_lights, _super);
  94094. function KHR_lights() {
  94095. var _this = _super !== null && _super.apply(this, arguments) || this;
  94096. _this.name = NAME;
  94097. return _this;
  94098. }
  94099. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94100. var _this = this;
  94101. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94102. var promise = _this._loader._loadSceneAsync(context, scene);
  94103. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94104. if (light.type !== LightType.AMBIENT) {
  94105. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94106. }
  94107. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94108. return promise;
  94109. });
  94110. };
  94111. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94112. var _this = this;
  94113. return this._loadExtensionAsync(context, node, function (context, extension) {
  94114. var promise = _this._loader._loadNodeAsync(context, node);
  94115. var babylonLight;
  94116. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94117. var name = node._babylonMesh.name;
  94118. switch (light.type) {
  94119. case LightType.AMBIENT: {
  94120. throw new Error(context + ": Ambient lights are not allowed on a node");
  94121. }
  94122. case LightType.DIRECTIONAL: {
  94123. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94124. break;
  94125. }
  94126. case LightType.POINT: {
  94127. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94128. break;
  94129. }
  94130. case LightType.SPOT: {
  94131. var spotLight = light;
  94132. // TODO: support inner and outer cone angles
  94133. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94134. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94135. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94136. break;
  94137. }
  94138. default: {
  94139. throw new Error(context + ": Invalid light type " + light.type);
  94140. }
  94141. }
  94142. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94143. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94144. babylonLight.parent = node._babylonMesh;
  94145. return promise;
  94146. });
  94147. };
  94148. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94149. get: function () {
  94150. var extensions = this._loader._gltf.extensions;
  94151. if (!extensions || !extensions[this.name]) {
  94152. throw new Error("#/extensions: " + this.name + " not found");
  94153. }
  94154. var extension = extensions[this.name];
  94155. return extension.lights;
  94156. },
  94157. enumerable: true,
  94158. configurable: true
  94159. });
  94160. return KHR_lights;
  94161. }(GLTF2.GLTFLoaderExtension));
  94162. Extensions.KHR_lights = KHR_lights;
  94163. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94164. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94165. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94166. })(BABYLON || (BABYLON = {}));
  94167. //# sourceMappingURL=KHR_lights.js.map
  94168. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94169. globalObject["BABYLON"] = BABYLON
  94170. return BABYLON;
  94171. });